为什么 Task 对象不使用传递给它的参数? [英] Why would Task object not use parameter passed to it?

查看:17
本文介绍了为什么 Task 对象不使用传递给它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Task 并行处理多个请求并向每个任务传递不同的参数,但似乎所有任务都采用一个最终参数并使用该参数执行方法.

I'm using Task to process multiple requests in parallel and passing a different parameter to each task but it seems all the tasks takes one final parameter and execute the method using that.

以下是示例代码.我期望输出为:

Below is the sample code. I was expecting output as:

0 1 2 3 4 5 6 ..99

0 1 2 3 4 5 6 ..99

但我明白了:

100 100 100 ..10 .

100 100 100 ..10 .

可能在调用print方法之前,i的值已经是100,但是每个方法不应该打印传递给它的参数吗?为什么print方法会取i的最终值?

May be before print method is called, i's value is already 100 but shouldn't each method print the parameter passed to it? Why would print method takes the final value of i?

class Program
{
    static void Main(string[] args)
    {
        Task[]t = new Task[100];
        for (int i = 0; i < 100; i++)
        {
            t[i] = Task.Factory.StartNew(() => print(i));
        }
        Task.WaitAll(t);
        Console.WriteLine("complete");
        Console.ReadLine();
    }

    private static void print(object i)
    {

        Console.WriteLine((int)i);
    }
}

推荐答案

你是 关闭.解决此问题的最简单方法是:

You're a victim of a closure. A simplest fix to this issue is:

    for (int i = 0; i < 100; i++)
    {
        int v = i;
        t[i] = Task.Factory.StartNew(() => print(v));
    }

您可以找到更详细的解释此处这里.

You can find more detailed explanations here and here.

这篇关于为什么 Task 对象不使用传递给它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆