为什么下面的值 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());
}
}