Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parallel.For() Not Async Friendly
using System.Threading.Tasks
void Main()
{
var options = new ParallelOptions() {
MaxDegreeOfParallelism = 2
};
Parallel.For(0, 10, options, i => ExecTaskSync(i));
Parallel.For(0, 10, options, async i => await ExecTask(i));
Console.WriteLine("ALL DONE.");
}
// Define other methods and classes here
async Task<int> ExecTask(int index)
{
Console.WriteLine($"Task {index} starting.");
await Task.Delay(1000);
Console.WriteLine($"Task {index} done.");
return index;
}
int ExecTaskSync(int index)
{
Console.WriteLine($"Sync Task {index} starting.");
Thread.Sleep(1000);
Console.WriteLine($"Sync Task {index} done.");
return index;
}
/**********
* OUTPUT *
***********
Sync Task 0 starting.
Sync Task 5 starting.
Sync Task 0 done.
Sync Task 1 starting.
Sync Task 5 done.
Sync Task 6 starting.
Sync Task 6 done.
Sync Task 7 starting.
Sync Task 1 done.
Sync Task 2 starting.
Sync Task 2 done.
Sync Task 3 starting.
Sync Task 7 done.
Sync Task 8 starting.
Sync Task 3 done.
Sync Task 8 done.
Sync Task 9 starting.
Sync Task 4 starting.
Sync Task 4 done.
Sync Task 9 done.
Task 0 starting.
Task 5 starting.
Task 1 starting.
Task 6 starting.
Task 7 starting.
Task 8 starting.
Task 9 starting.
Task 3 starting.
Task 4 starting.
Task 2 starting.
ALL DONE.
Task 2 done.
Task 4 done.
Task 9 done.
Task 0 done.
Task 8 done.
Task 3 done.
Task 7 done.
Task 5 done.
Task 6 done.
Task 1 done.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment