我有一个长期运行的工作,我需要为集合中的每个项目运行一次。
我想同时做这些工作,虽然整个程序可以等待所有工作完成。(稍后我可能会更改它,但就目前而言,我让问题保持简单)
根据已经提供的一些帮助,我得到了以下模式:
public static void DoWork()
{
//Get a collection of items
var items = GetMyItems();
}
private async void DoStuffWithItems(ICollection<MyItem> items)
{
var tasks = items.Select (i => DoStuffWithItem(i));
await Task.WhenAll(tasks);
}
private Task DoStuffWithItem(MyItem item)
{
//LongRunningTask
return Task.Run(async () =>
{
var returnObject = await LongRunningAsyncMethod(item);
});
}
Run Code Online (Sandbox Code Playgroud)
如果我理解正确的话,这仍然一次完成每项任务 - 毫无意义。
有人建议我将 Parallel.ForEach 与 async await 结合使用 - Parallel-ForEach 模式很简单:
public static void DoWork()
{
//Get a collection of items
var items = GetMyItems();
Parallel.ForEach(items, (item) …Run Code Online (Sandbox Code Playgroud)