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

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

问题描述

您好,我将 _noOfThreads 作为定义的任务一次运行.所以我继续使用 % 操作符继续任务,在循环结束时我有 Tasks.WaitAll.这是代码片段.

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 之后的下一行就会被执行.如何更改此代码以等待子任务?

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];

将您的代码更改为:

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

试试看!祝你好运:)

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

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