Task.ContinueWith不工作我如何预期 [英] Task.ContinueWith not working how I expected
问题描述
考虑下面的代码。我开始与什么都不做的任务,然后使用ContinueWith()启动10个呼叫递增计数器的方法。
Consider the following code. I am starting with a task that does nothing, and then using ContinueWith() to start 10 calls to a method that increments a counter.
当我运行这个程序,它打印0,表明该增量()方法尚未在所有调用。我期待它被称为10倍,因为这是我多少次叫ContinueWith()。
When I run this program, it prints "0", indicating that the increment() method hasn't been called at all. I was expecting it to be called 10 times, since that's how many times I called ContinueWith().
如果我取消了Thread.sleep代码(20)行,然后它打印预期10。
If I uncomment the "Thread.Sleep(20)" line, then it prints "10" as expected.
这发生在任何释放或调试模式。我的系统是运行Windows 7的x64核心2四核超线程(8个逻辑核心)。
This happens in either release or debug mode. My system is a core 2 quad with hyperthreading (8 logical cores) running Windows 7 x64.
我想我有某种根本性的误解有关如何Task.ContinueWith()工程....
I assume I have some kind of fundamental misunderstanding about how Task.ContinueWith() works....
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main()
{
using (var task = Task.Factory.StartNew(()=>{}))
{
for (int i = 0; i < 10; ++i)
{
task.ContinueWith(_=> increment());
// Thread.Sleep(20); // Uncomment to print 10 instead of 0.
}
task.Wait();
}
// This prints 0 UNLESS you uncomment the sleep above.
Console.WriteLine(counter);
}
static void increment()
{
Interlocked.Increment(ref counter);
}
private static int counter;
}
}
任何人都可以阐明这是怎么回事任何光线?
Can anyone shed any light on what's going on here?
推荐答案
原因很简单:你等待一个已经完成了任务。你真正需要的是等待你在循环中创建的十大任务:
The reason is simple: You wait on the task that is already finished. What you really want is to wait for the ten tasks you created in the loop:
var tasks = new List<Task>();
for (int i = 0; i < 10; ++i)
{
tasks.Add(task.ContinueWith(_=> increment()));
}
Task.WaitAll(tasks.ToArray());
这篇关于Task.ContinueWith不工作我如何预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!