任务和增量值 [英] Task and increment value

查看:68
本文介绍了任务和增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了代码:

List<Task> tt = new List<Task>();
for (int i = 0; i < 5; i++)
{
    tt.Add(
    new Task((o) =>
    {
        Thread.Sleep(Convert.ToInt32(o)*1000);
        Console.WriteLine("end of {0}!", Convert.ToInt32(o));
    },i));
}

tt.ForEach(t => t.Start());
Task.WaitAll(tt.ToArray());

它在控制台中显示给我:结束 1!(间隔 1 秒)

and it show me in console: end of 1! (interval 1 sec)

2 结束!(间隔 1 秒)

end of 2! (interval 1 sec)

3 结束!(间隔 1 秒)

end of 3! (interval 1 sec)

4 结束!(间隔 1 秒)

end of 4! (interval 1 sec)

5 结束!(间隔 1 秒)

end of 5! (interval 1 sec)

但是如果我得到这个代码:

but if i get this code:

List<Task> tt = new List<Task>();
for (int i = 0; i < 5; i++)
{
    tt.Add(
    new Task( () =>
    {
        Thread.Sleep(i*1000);
        Console.Write("end! ");
    }));
}

tt.ForEach(t => t.Start());
Task.WaitAll(tt.ToArray());

然后我有这个答案:(间隔 5 秒,全部在一瞬间):结尾!结尾!结尾!结尾!结束!

then i have this answer: (interval 5 seconds and all in one moment): end! end! end! end! end!

你能解释一下这个现象吗?

Could you explain me this phenomenon?

我认为:

这是因为变量i"不断递增并且线程可以访问这些变量?在这种情况下,每个线程都会记住最后一个值i",因此每个线程将等待 5 秒并发送消息?

This is due to the fact that the variable "i" is continuously incremented and thread has access to the variables? In this case, each thread will remember the last value "i" so each thread will wait for 5 seconds and just send a message?

这是一个很好的理由吗?

It's good reason?

推荐答案

在第二种情况下,使用 i 的最后一个值是 5 由于 捕获循环变量的闭包,可以将循环变量的值赋值给一些局部变量并在任务中使用它,

In the second case the last value of i is used which is 5 due to capture closure of loop variable, you can assign the value of loop variable to some local variable and use that in task,

List<Task> tt = new List<Task>();
for (int i = 0; i < 5; i++)
{
    int temp = i;
    tt.Add(
    new Task( () =>
    {
        Thread.Sleep(temp * 1000);
        Console.Write("end! ");
    }));
}

tt.ForEach(t => t.Start());
Task.WaitAll(tt.ToArray());

这篇关于任务和增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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