对多个任务使用ContinueWith [英] Using ContinueWith with Multiple Tasks

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

问题描述

这并不像我想的那样简单,需要启动许多任务来对对象进行操作.每个任务一个唯一的对象.第二部分是每个任务报告结果时的ContinueWith.但是,我没有得到WhenAll类型的行为.希望有人能使我挺直.

This is not behaving quite as I thought it would the need is simple, launch a number of tasks to do operations on an object. One unique object per task. The second part is a ContinueWith when each task reports the results. However, I am not getting a WhenAll type behavior. Hopefully someone can set me straight.

_tasks = new Task<AnalysisResultArgs>[_beansList.Count];
for (int loopCnt = 0; loopCnt < _beansList.Count; loopCnt++)
{
    _tasks[loopCnt] = Task<AnalysisResultArgs>.Factory.StartNew(() =>
    {
        return _beansList[loopCnt].Analyze(newBeanData);
    });
    await _tasks[loopCnt].ContinueWith(ReportResults, 
                  TaskContinuationOptions.RunContinuationsAsynchronously)  
    // do some housekeeping when all tasks are complete          
}

private void ReportResults(Task<AnalysisResultArgs> task)
{
     /* Do some serial operations
}

据我了解,将启动_beansList.Count任务,并且通过在ContinueWith上使用await,直到所有任务都完成后,整理工作才能执行.我无法阻止,因为我需要确保能够限制传入的数据,以防止太多的任务等待执行.

It was my understanding that _beansList.Count tasks would be launched and by using await on the ContinueWith the housekeeping work won't execute until all the Tasks have completed. I cannot block, as I need to be sure to be able to throttle the incoming data to prevent way too many tasks waiting to be executed.

我到哪里去了,等待实际上完成了,即使不是所有任务都已完成,客房服务也可以运行.

Where did I goof, the await actually completes and the housekeeping gets run even though not ALL of the tasks have run to completion.

推荐答案

您没有等待所有任务,而是在等待循环的继续.您应该为此使用Task.WhenAll方法.另外,如果可以在任务中运行它,为什么还需要延续?像这样简化代码:

You do not await all the tasks, you're awaiting the continuation in loops. You should use the Task.WhenAll method for this. Also, why do you need the continuation, if you can run it inside task? Simplify your code like this:

private void ReportResults(AnalysisResultArgs results)
{
     /* Do some serial operations */
}

...
_tasks = new Task<AnalysisResultArgs>[_beansList.Count];
for (int loopCnt = 0; loopCnt < _beansList.Count; loopCnt++)
{
    var count = loopCnt;
    _tasks[count] = Task.Run(() =>
    {
        var results = _beansList[count].Analyze(newBeanData);
        ReportResults(results);
        return results;
    });
}

// do some housekeeping when all tasks are complete          
await Task.WhenAll(_tasks);

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

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