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); } } }
source share