Asynchronous foreach

2019-02-16 21:35发布

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.

2条回答
Rolldiameter
2楼-- · 2019-02-16 21:54

Your target method would have to return a Task

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

Processing ids would be done like this

// This Gets all the ID(s)-IEnumerable <int>
var clientIds = new Clients().GetAllClientIds(); 
// This gets all the tasks to be executed
var tasks = clientIds.Select(id => ProcessId(id)).
// this will create a task that will complete when all of the `Task` 
// objects in an enumerable collection have completed. 
await Task.WhenAll(tasks);
查看更多
时光不老,我们不散
3楼-- · 2019-02-16 22:17

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.

查看更多
登录 后发表回答