Task.WaitAll不会等待子任务? [英] Task.WaitAll doesn't wait for child task?

查看:302
本文介绍了Task.WaitAll不会等待子任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有 _noOfThreads 定义任务同时运行。所以我一直用运营商,在循环我有 Tasks.WaitAll 的一端延续的任务。这是code段。

Hello I have _noOfThreads as defined tasks to run at a time. So I keep continuing the Tasks by using % operator and at the end of the loop I have Tasks.WaitAll. This is the code snippet.

for (int index = 0; index < count; index++)
{

                if (index < _noOfThreads)
                    tasks[index] = Task.Factory.StartNew(somedelegate);
                else
                    tasks[index % _noOfThreads].ContinueWith(task => { foo.bar(); }, 
                            TaskContinuationOptions.AttachedToParent);
 }
  Task.WaitAll(tasks);

不过,我注意到它没有等待子任务的完成。只要父任务完成后, Task.WaitAll 的下一行被执行。我要如何改变这种code,以等待子任务还?

However, I notice it doesn't wait for child tasks to complete. As soon as the parent tasks complete, the next line after Task.WaitAll gets executed. How do I change this code to wait for child tasks also?

推荐答案

我觉得你分配你的任务:

I think you are allocating your Tasks as:

Tasks[] tasks = new Task[ _noOfThreads];

更改code是:

Change your code to be:

Tasks[] tasks = new Task[count];

for (int index = 0; index < count; index++)
{

    if (index < _noOfThreads)
         tasks[index] = Task.Factory.StartNew(somedelegate);
    else
         tasks[index] = tasks[index % _noOfThreads].ContinueWith(task => { foo.bar(); }, 
                            TaskContinuationOptions.AttachedToParent);
}
Task.WaitAll(tasks);

试试看吧!好运:)

Give it a try! Good Luck :)

这篇关于Task.WaitAll不会等待子任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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