This question has already been answered:

You need to run N number of parallel streams and output the data to the form ( ListBox ) interactively from them. This is approximately what happens:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private string name; private static List<string> listing = new List<string>(); private void button1_Click(object sender, EventArgs e) { for (int i=1 ; i<5; i++) { name = i.ToString(); Work w = new Work(name); Thread t = new Thread(new ThreadStart(w.DoWork)); t.Start(); } } class Work { private string m_name; public Work(string name) { m_name = name; } public void DoWork() { for (int x = 0; x < 10; x++) { Form1.listing.Add(string.Format("Thread is working: {0} - Cycle: {1}", m_name, x)); // Form1.list1.Items.Add(string.Format("Thread is working: {0} - Cycle: {1}", m_name, x)); } } } private void button2_Click(object sender, EventArgs e) { list1.DataSource = listing; } } 

Reported as a duplicate by members andreycha , aleksandr barakin , Abyx , user194374, Community Spirit Jan 17 '16 at 9:34 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

In this case, you can use the Invoke method. It allows you to call some delegate from the thread associated with the specified control (usually with the form).

But I advise you to use a more modern way:

 private void button1_Click(object sender, EventArgs e) { for (int i=1; i<5; i++) DoWork(i.ToString()); } private async void DoWork(string name) { for (int x = 0; x < 10; x++) { var y = await Task.Run(() => { return x; }); // Изображаем асинхронную работу в фоновом потоке list1.Items.Add(string.Format("Thread is working: {0} - Cycle: {1}", m_name, y)); await Task.Delay(1000); } } 

The main point: the loop inside the DoWork "spinning" in the main thread, and therefore there are no problems with access from it to the form components. "Long" operations are either transferred to the thread pool (for example, the "calculation" of the variable y ) Task.Delay special asynchronous API is used, which allows you not to occupy the stream at all (for example, Task.Delay ).

From the point of view of the calling function ( button1_Click ), the DoWork function returns control as soon as the first await statement starts to execute in it.

  • Thanks for the decision. Now let's try))) - Oscar OS