可能是重复问题:
C#中的捕获变量循环
我对多线程编程还不是很熟悉。当我运行下面的代码时,只有最后一个子任务被执行了。请问发生了什么事情?非常感谢。
private void Process()
{
Dictionary<int, int> dataDict = new Dictionary<int, int>();
dataDict.Add(1, 2000);
dataDict.Add(2, 1000);
dataDict.Add(3, 4000);
dataDict.Add(4, 3000);
foreach (KeyValuePair<int, int> kvp in dataDict)
{
Console.WriteLine("Ready for [" + kvp.Key.ToString() + "]");
Task.Factory.StartNew(() => DoSomething(kvp.Value, kvp.Key));
}
private static void DoSomething(int waitTime, int childID)
{
{
Console.WriteLine("Start task [" + childID.ToString() + "]");
Thread.Sleep(waitTime);
Console.WriteLine("End task [" + childID.ToString() + "]");
}
}
输出Ready for [1]
Ready for [2]
Ready for [3]
Ready for [4]
Start task [4]
Start task [4]
Start task [4]
Start task [4]
End task [4]
End task [4]
End task [4]
End task [4]