我路過INT變量任務時經常會奇怪resulst如下面的例子:傳遞非參考價值任務
List<List<object>> ListToProcess = new List<List<object>>();
// place some lists in list to process
foreach (var temp in Foo)
ListToProcess.Add(temp);
foreach (var tempArray in ListToProcess)
{
// initialize each list in ListToProcess
}
int numberOfChunks = ListToProcess.Count;
Task[] tasks = new Task[numberOfChunks];
for (int counter = 0; counter < numberOfChunks; counter++)
{
tasks[counter] = Task.Factory.StartNew(() =>
{
// counter is always = 5 why? <---------------------------
var t = ListToProcess[counter];
});
}
我怎樣才能解決這個問題?
閉包捕獲變量,而不是值。 請參閱http://stackoverflow.com/questions/271440/c-sharp-captured-variable-in-loop – 2012-04-11 23:00:00