Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous 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  
}

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.

like image 719
alomegah Avatar asked Oct 17 '16 16:10

alomegah


2 Answers

Now, in .NET 6 there is already a built-in Parallel.ForEachAsync

See: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.foreachasync?view=net-6.0 https://www.hanselman.com/blog/parallelforeachasync-in-net-6

like image 55
Pawel Troka Avatar answered Oct 23 '22 19:10

Pawel Troka


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);
like image 29
Nkosi Avatar answered Oct 23 '22 18:10

Nkosi