The task does not change the parameters.

I play with Task functions and found a rather strange problem: I run Task in for loop and pass parameters for function (i) the number of cycles is 100. Since I expected the output to be like this. 1
2
3
4
5
But the output that I get from this function is 100
100
100
I mean that it will not change to the new parameters. For more details, I downloaded the entire project.

Download the sample program I created!

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => button_tast()); } void button_tast() { Task[] tk =new Task[100]; for (int i = 0; i < 100; i++) { tk[i] = Task.Factory.StartNew(() => taskThread(i)); } Task.WaitAll(tk); } void taskThread(int i){ listBox1.Items.Add(i); } } } 
+4
source share
2 answers

This is because you are closing the loop variable . You can rewrite the loop as

 for (int i = 0; i < 100; i++) { int taskNumber = i tk[i] = Task.Factory.StartNew(() => taskThread(taskNumber)); } 

and you will be fine

+8
source

The problem is that, from the point of view of Tasks, the variable i is global and can be changed in a non-threading way. It is easy to fix, though ....

  for (int i = 0; i < 100; i++) { int localCopy = i; tk[i] = Task.Factory.StartNew(() => taskThread(localCopy)); } 
0
source

Source: https://habr.com/ru/post/1481769/


All Articles