1

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

    }
}
4

1 回答 1

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 dangerous

话虽如此,在这种情况下,您正在为序列中的每个元素执行“任务”。您可能需要考虑使用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
于 2013-02-11T21:47:33.423 回答