gpt4 book ai didi

c# - 值总是一样的

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:53 25 4
gpt4 key购买 nike

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

}
}

最佳答案

您正在关闭循环值。您需要将临时变量移动到外部范围:

    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

关于c# - 值总是一样的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14821428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com