Asynchronous : Async Await (.NET) Avoid Context Switching to Improve Performance
In an application with user interface, the UI should only be updated on a UI thread (context). Other I/O or CPU bound works should be handled by worker threads from thread pool and not by the UI thread.
Let us look at a simple mobile application
For example, there is a mobile single page weather application. The app has a load weather forecast button : “Load_button” and a list view showing the weather forecast for 7 days. When an user clicks on the “Load_button”, the application makes an API call to get the weather data. The weather data is then processed to populate the list view.
Lets look at a code snippet where context switch is not avoided!
From the above code snippet :
- UI thread should be responsible for only UI changes e.g updating list view, showing load animation etc.
- The unnecessary context switch can cause potential lag where the UI might become less responsive.
- Each method should be separated such that it has its own context i.e UI changes and non-UI changes e.g deserializing json should be in separate methods.
- This performance hit can be improved by avoiding context for non-UI work which does not need to run on UI thread. Instead a thread from thread pool can do work like deserializing json etc.
How can we improve it? What is the best practice?
Lets have a look at the code snippet below:
From the above code snippet :
- Each method is separated such that each have their own context
a. LoadWeatherButton_Click : UI context
b. GetWeatherData : thread pool thread - ConfigureAwait is set to false so that the original context (UI thread) is not captured when awaiting. Thus the worker thread can resume work after getting the initial weather data.
Rule of thumb is use ConfigureAwait(false) unless you know you do need the context.
I hope you found this article useful. In my next article we will discuss how to prevent deadlock when using async await. This is important because a deadlock will freeze an application and will result in a bad user experience.