异步 foreach

扫码查看
本文介绍了异步 foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 C# 中实现异步 foreach?其中 id(s) 将被方法异步处理,而不是使用 Parallel.ForEach

is there a way for an Asynchronous foreach in C#?where id(s) will be processed asynchronously by the method, instead of using Parallel.ForEach

//This Gets all the ID(s)-IEnumerable <int>
var clientIds = new Clients().GetAllClientIds();

Parallel.ForEach(clientIds, ProcessId); //runs the method in parallel

static void ProcessId(int id)
{
// just process the id
}

应该是一个foreach但异步运行的东西

should be something a foreach but runs asynchronously

foreach(var id in clientIds)
{
   ProcessId(id) //runs the method with each Id asynchronously??
}

我正在尝试在控制台中运行程序,它应该在关闭控制台之前等待所有 ID 完成处理.

i'm trying to run the Program in Console, it should wait for all id(s) to complete processing before closing the Console.

推荐答案

不,这不可能.

而是在 foreach 循环中添加您想要执行的任务作为任务集合,然后使用 Task.WaitAll.

Instead in foreach loop add what you want to do as Task for Task collection and later use Task.WaitAll.

var tasks = new List<Task>();

foreach(var something in somethings)
 tasks.Add(DoJobAsync(something));

await Task.WhenAll(tasks);

注意方法 DoJobAsync 应该返回 Task.

Note that method DoJobAsync should return Task.

更新:

如果您的方法不返回 Task 而是返回其他内容(例如 void),您有两个基本相同的选项:

If your method does not return Task but something else (eg void) you have two options which are essentially the same:

1.将 Task.Run(action) 添加到任务集合中

1.Add Task.Run(action) to tasks collection instead

tasks.Add(Task.Run(() => DoJob(something)));

2. 将您的同步方法包装在返回 Task 的方法中

2.Wrap your sync method in method returning Task

 private Task DoJobAsync(Something something)
 {
     return Task.Run(() => DoJob(something));
 }

如果您想从任务执行中接收一些结果,您也可以使用 Task 泛型.

You can also use Task<TResult> generic if you want to receive some results from task execution.

这篇关于异步 foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:18
查看更多