I am playing with Task functions and found a pretty strange problem that I run Task in for loop and pass the parameters to function (i) the loop count is 100.
As I expected the output would be like this.
1
2
3
4
5
But the output I get from this function is
100
100
100
I mean it won't change to new parameters. For more details I uploaded the whole project. 
Download Sample Program that I made!
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);
}
}
}
                It's because you're closing over 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'll be fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With