Task.ContinueWith not working how I expected

試著忘記壹切 提交于 2019-12-05 09:35:04

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());

Sure. You're printing out the value when the initial task has completed - you're not waiting for the continuation to occur. In other words, when the initial task completes, 11 things happen:

  • 10 new tasks start executing, each incrementing the counter
  • You print out the counter

You could effectively chain all these together if you want:

task = task.ContinueWith(_=> increment());

Then when the original task finishes, one incrementer will fire. When that finishes, the next incrementer will fire. When that finishes [...]. And when the final incrementer has finished, your Wait call will return.

If you change the main body as follows:

        using (var task = Task.Factory.StartNew(() => { }))
        {
            var t = task;
            for (int i = 0; i < 10; ++i)
            {
               t = t.ContinueWith(_ => increment());
                // Thread.Sleep(20);  // Uncomment to print 10 instead of 0.
            }

            t.Wait();
        }

You will get 10 without sleeping. The main change is t = t.ContinueWith(...) and t is necessary because you're not allowed to change the using() variable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!