Optimizing async/await codes with TPL
Tingwei
Posted on April 30, 2021
I was wondering how to optimize the performance of async/await codes with TPL(Task Parallel Library).
Therefore, I tested different amount of tasks(10/1000/5000) separately, and each task took 5 seconds.
- The result :
Without TPL | With TPL | |
---|---|---|
100 tasks | 500 sec | 27.91 sec (MaxDegreeOfParallelism = 20) |
1000 tasks | 5000 sec | 135.34 sec (MaxDegreeOfParallelism = 70) |
5000 tasks | 25000 sec | 317.33 sec (MaxDegreeOfParallelism = 130) |
- The testing code :
public async Task GetTasks()
{
try
{
Stopwatch sw = new Stopwatch();
// start
sw.Start();
var workBlock = new ActionBlock<int>((a) => GetTask(a),
new ExecutionDataflowBlockOptions
{
//Gets the maximum number of messages that may be processed by the block concurrently(from MSDN)
MaxDegreeOfParallelism = 5
});
// 100 tasks
foreach(var taskIndex in Enumerable.Range(1, 100))
{
workBlock.Post(taskIndex);
}
workBlock.Complete();
await workBlock.Completion;
// stop
sw.Stop();
Console.WriteLine($"{sw.ElapsedMilliseconds}ms");
} catch
{
throw;
}
}
public async Task GetTask(int a)
{
// mock http request
await Task.Delay(5000);
}
Thank you!
💖 💪 🙅 🚩
Tingwei
Posted on April 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.