为什么值X总是=到值“int.Parse(radTextBoxFloodRequests.Text)”而不是值i?
C#代码
private void radButtonTaskWithStatus_Click(object sender, EventArgs e)
{
try
{
Task<int>[] tasks = new Task<int>[int.Parse(radTextBoxFloodRequests.Text)];
for (int i = 0; i < int.Parse(radTextBoxFloodRequests.Text); i++)
{
tasks[i] = new Task<int>(() =>
{
int x = i;
int result = TaskRequestWithResult(int.Parse(radTextBoxFirstNumber.Text), int.Parse(radTextBoxSecondNumber.Text), int.Parse(radTextBoxFloodDelay.Text), x);
return result;
});
}
var continuation = Task.Factory.ContinueWhenAll(
tasks,
(antecedents) =>
{
int total = 0;
for (int i = 0; i < int.Parse(radTextBoxFloodRequests.Text); i++)
total = total + tasks[i].Result;
Debug.Print("Finished - Sum of all results is: " + total);
MessageBox.Show("Finished - Sum of all results is: " + total);
});
for (int i = 0; i < int.Parse(radTextBoxFloodRequests.Text); i++)
tasks[i].Start();
// Use next line if you want to block the main thread until all the tasks are complete
//continuation.Wait();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
答案 0 :(得分:6)
你正在关闭循环值。您需要将临时变量移动到外部范围:
for (int i = 0; i < int.Parse(radTextBoxFloodRequests.Text); i++)
{
int x = i; // This was in the wrong scope
tasks[i] = new Task<int>(() =>
{
int result = TaskRequestWithResult(int.Parse(radTextBoxFirstNumber.Text), int.Parse(radTextBoxSecondNumber.Text), int.Parse(radTextBoxFloodDelay.Text), x);
return result;
});
}
有关发生这种情况的详细信息,请参阅Eric Lippert的Closing over the loop variable considered harmful。
话虽如此,在这种情况下,您正在为序列中的每个元素执行“任务”。您可能需要考虑使用Parallel.For
而不是一系列任务,因为在意图方面可能会更清楚。
int firstNum = int.Parse(radTextBoxFirstNumber.Text);
int secondNum = int.Parse(radTextBoxSecondNumber.Text);
int delay = int.Parse(radTextBoxFloodDelay.Text);
var task = Task.Factory.StartNew(() =>
{
int total;
Parallel.For(0, int.Parse(radTextBoxFloodRequests.Text),
() => 0,
(i, loopState, localState) =>
{
return localState + TaskRequestWithResult(firstNum, secondNum, delay, i);
},
localTotal => Interlocked.Add(ref total, localTotal);
return total;
};
var continuation = task.ContinueWith(
antecedent =>
{
int total = antecedent.Result;
Debug.Print("Finished - Sum of all results is: " + total);
MessageBox.Show("Finished - Sum of all results is: " + total);
}); // Can use scheduler here if you want to update UI values