DEV Community

loading...

Optimizing async/await codes with TPL

Tingwei
・1 min read

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 :

ActionBlock

MaxDegreeOfParallelism

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);
}

Enter fullscreen mode Exit fullscreen mode

Thank you!

Discussion (1)

Collapse
tingwei628 profile image
Tingwei Author

Here's another great post by @cgillum to discuss about the similar topic.