ConfigureAwait in C#

heybaldur

HeyBaldur

Posted on May 15, 2023

ConfigureAwait in C#

When we use the await keyword to asynchronously wait for a task to complete, the current synchronization context is captured and used to resume the execution of the rest of the method after the awaited task completes.

This means that if the awaited task completes on a different thread than the one that started the method. However, in some cases, it may not be necessary or desirable to resume on the original synchronization context.

We can use the ConfigureAwait(false) method to explicitly specify that the continuation of the method can run on any thread, rather than the original synchronization context. This can help to improve performance and reduce the risk of deadlocks or other synchronization issues.

ConfigureAwait(false) can be used for improving performance and reduce the risk of synchronization issues in cases where the continuation of the method does not need to run on the original synchronization context.



int sum = await Task.Run(() => 
{
   if (Thread.CurrentThread.Name == null)
   {
      Thread.CurrentThread.Name = Guid.NewGuid().ToString();
   }

   Console.WriteLine($"Task.Run running on thread id: 
   {Thread.CurrentThread.Name}");

    return a + b;
}).ConfigureAwait(false);


Enter fullscreen mode Exit fullscreen mode

If you want to see this code in action, just get the code from the repository in GitHub where I use two different methods, one with the ConfigureAwait and the other without it.

You can run it locally and see the results in the console for better understanding.

Bonus:
You can also tab in Visual Studio => Debug => Windows => Threads you will be able to visualize also the code in execution.

Image description

If you find this explanation and code useful, please follow me on:

Happy coding!

💖 💪 🙅 🚩
heybaldur
HeyBaldur

Posted on May 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ConfigureAwait in C#
csharp ConfigureAwait in C#

May 15, 2023