异步的foreach [英] Asynchronous foreach

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

问题描述

有没有一种方式在C#中的异步foreach?
其中id将由方法异步处理,而不是使用 Parallel.ForEach

  //获取所有的ID(s)-IEnumerable< int> 
var clientIds = new Clients()。GetAllClientIds();

Parallel.ForEach(clientIds,ProcessId); //并行运行方法

static void ProcessId(int id)
{
//只处理id
}


$ b

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

  foreach(在id的ID)
{
ProcessId(id)/ /异步运行每个Id的方法?



$ b我试图在控制台中运行程序,它应该等待所有在关闭控制台之前完成处理。

解决方案

不,这是不可能的。 foreach循环添加你想做的任务为任务收集和稍后使用Task.WaitAll。

  var tasks = new List<任务>(); 

foreach(var某些东西)
tasks.Add(DoJobAsync(something));

等待Task.WhenAll(任务);

请注意,方法DoJobAsync应该返回任务。

<如果你的方法没有返回任务,而是其他的东西(比如void),那么你有两个选项基本上是一样的:
$ b $ 1.将Task.Run(action)添加到任务集合中而不是

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

2.在返回任务的方法中包装同步方法

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





$ b您也可以使用任务< TResult> code> generic,如果你想从任务执行中收到一些结果。


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  
}

should be something a foreach but runs asynchronously

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

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

解决方案

No, it is not really possible.

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

Note that method DoJobAsync should return Task.

Update:

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

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

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

2.Wrap your sync method in method returning Task

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

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

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

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