Chapter 1.7 C# – Async and Await
When your application is executing and I/O operation on the primary application thread. Windows notices that your thread is waiting for the I/O operation to complete.
Windows pauses your thread so that it doesn’t use any CPU resources, but while doing this it still uses memory & the thread can’t be used to serve other requests, this will lead to new threads being created if new requests come in.
Async code fixes this, instead of blocking the thread until the I/O operation finishes, you get back a TASK object that represents the result of the async operation. By setting a continuation on the Task you can continue when the I/O is done.
The await function cannot be used in main, we therefore wait for the result to be returned and capture that instead.
Using Await might not improve performance, it will improve responsiveness. The await keyboard also makes sure that the remainder of the of your methods run on correct UI thread so it can be updated.
When exceptions happen in an async method you normally expect a AgregateException. However the generated code helps you unwrap the AggregateException and throws the first of its inner exceptions. This makes it more intuitive and easier to debug.
Connects the application model to the threading model.
A WPF app users a single UI and multiple background threads to improve responsiveness
ASP.NET uses threads from the thread pool that are initialised with the correct data, such as user data and culture to server incoming requests
Abstracts the way these different applications work and makes sure that you end up on the right thread when you need to update something on the UI or process the web request.
The await keyword makes sure the current SynchronizationContext is saved and restored when the task finishes.
You can configure the await to be false, it will perform better but if it requires a UI thread you cannot use this.
You should avoid calling returning void as it is not checked, also do not mark a function as await.