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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With