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.
Your target method would have to return a Task
Processing ids would be done like this
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.
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
2.Wrap your sync method in method returning Task
You can also use
Task<TResult>
generic if you want to receive some results from task execution.