C # WinForm. Thread starts and runs, but blocks all form elements. What am I doing wrong? If there is a need, I can show the code, it is short.

namespace InvokeTest { public partial class MyForm:Form { public delegate void AddListItem(); public AddListItem myDelegate; private Thread myThread; int count; public bool bStop; public MyForm() { InitializeComponent(); myDelegate += new AddListItem(AddListItemMethod); count = 0; bStop = true; } public void AddListItemMethod() { String myItem; while(!bStop) { ++count; myItem = "MyListItem" + count.ToString(); myListBox.Items.Add(myItem); myListBox.Update(); Thread.Sleep(1000); } myThread.Abort(); } private void button1_Click(object sender, EventArgs e) { myThread = new Thread(new ThreadStart(ThreadFunction)); bStop = false; myThread.Start(); } private void ThreadFunction() { myListBox.Invoke(myDelegate);//моя вставка } private void button2_Click(object sender, EventArgs e) { textBox1.Text = "Stop"; bStop = true; } } } 

1 answer 1

You execute the AddListItemMethod code in the UI stream (of course, since you are accessing UI elements there!), And in it you cannot use Sleep for delay.

The code that creates a new thread, and then from a new thread, it launches AddListItemMethod via Invoke - this is a complicated method to run the code synchronously.

(Well, you use Thread.Abort , you can't do that at all.)

Correctly do as described in this answer .

 public partial class MyForm : Form { int count = 0; bool bStop = true; public MyForm() { InitializeComponent(); } async Task AddListItemMethod() { String myItem; while (!bStop) { ++count; var myItem = "MyListItem" + count.ToString(); myListBox.Items.Add(myItem); myListBox.Update(); // это всё ещё нужно? await Task.Delay(1000); } } async void button1_Click(object sender, EventArgs e) { bStop = false; await AddListItemMethod(); } void button2_Click(object sender, EventArgs e) { textBox1.Text = "Stop"; bStop = true; } }