Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigureAwait(false) performance test

Everywhere I read that I should use ConfigureAwait(false) to avoid deadlocks and for performance reasons. We are using ConfigureAwait in our application. But might remove the ConfigureAwaits as it's causing a different thread's execution context.

The different thread's execution context is causing (sometimes) problems with translations. As the set culture in currentculture and currentUICulture is not accessible on a different execution context.

I have tested it a little bit with the code below. It did not make any performance difference. I understand it's not a good test as with this simple test there are not many threads used.

static async Task MyMethodAsync()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10).ConfigureAwait(continueOnCapturedContext: false);
  }
  stopwatch.Stop();
  Console.WriteLine("Await: " + stopwatch.Elapsed.ToString());
}

static async Task MyMethodAsyncNoAwait()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10);
  }
  stopwatch.Stop();
  Console.WriteLine(stopwatch.Elapsed.ToString());
}

How should I test this properly? Is it a really bad idea of removing all ConfigureAwaits?

like image 392
1408786user Avatar asked Dec 19 '25 06:12

1408786user


1 Answers

Don't use ConfigureAwait blindly for performance. Use it when writing code (usually library code) where resuming on the same thread/synchronization context doesn't matter. If resuming on the right thread/synchronization context does matter, ConfigureAwait(false) will break your code, and then it doesn't matter how fast it could have been.

like image 60
Jesper Avatar answered Dec 20 '25 20:12

Jesper