简体   繁体   English

如何将两个任务集合链接在一起?

[英]How to chain together two collections of Tasks?

I'm attempting to run a collection of tasks, then once these have finished, run a separate collection of tasks. 我试图运行一组任务,然后在完成这些任务后,运行一个单独的任务组。 Essentially, the first collection of tasks are responsible for writing to some database tables, and the final collection of tasks collates the data from these tables into a reporting table. 本质上,第一个任务集合负责写入一些数据库表,最后一个任务集合将这些表中的数据整理到报告表中。

An example of the code I'm using is below: 我正在使用的代码示例如下:

var dbWriteTasks = clients.Select(c => DoSomeWorkAsync(c)).ToArray();
var dbCollateTasks = clients.Select(c => DoSomeOtherWorkAsync(c));

Task.Factory.ContinueWhenAll(dbWriteTasks, t => dbCollateTasks.ToArray());

This is running the first set of tasks successfully, but isn't running any of the second set of tasks, so I'm evidently doing something wrong. 这正在成功运行第一组任务,但没有运行第二组任务中的任何一个,因此我显然做错了。

I've also tried this to no avail: 我也试过了,但无济于事:

var dbWriteTasks = clients.Select(c => DoSomeWorkAsync(c)).ToArray();
var dbCollateTasks = clients.Select(c => DoSomeOtherWorkAsync(c)).ToArray();

Task.Factory.ContinueWhenAll(dbWriteTasks, t => dbCollateTasks);

This runs both sets of tasks, but the second set starts running and processing the data before the first set of tasks has finished inserting it... 这将同时运行两组任务,但是第二组任务将在第一组任务完成插入之前开始运行并处理数据。

I should also mention that I've tried running the two sets of tasks synchronously using Task.WaitAll but this hasn't worked either. 我还应该提到,我已经尝试使用Task.WaitAll同步运行这两套任务,但这也没有用。 I'm trying to do all of this inside an Azure function and Task.WaitAll just causes it to stop. 我正在尝试在Azure函数和Task.WaitAll执行所有这些Task.WaitAll只是使其停止。

I'm relatively new to the TPL, so any advice would be greatly appreciated! 我是TPL的新手,所以任何建议都将不胜感激!

Instead of the factory methods use await Task.WhenAll . 可以使用await Task.WhenAll代替工厂方法。 Using await allows you to seamlessly create continuations that read like synchronous code. 通过使用await ,您可以无缝创建类似于同步代码的连续读法。

var dbWriteTasks = clients.Select(c => DoSomeWorkAsync(c))
var dbCollateTasks = clients.Select(c => DoSomeOtherWorkAsync(c));

await Task.WhenAll(dbWriteTasks);
await Task.WhenAll(dbCollateTasks);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM