What does async and await really do?
await keyword is basically just waiting for whatever function that comes after that keyword to create a thread, do work and return to the calling thread once it is done.
Everything that comes after is a “continuation”
The following 2 functions do pretty much the same thing
The above should also indicate something else, namely continuation.
In the first method everything after the “Task” calls would probably run before the tasks would finish.
In the latter, everything after the await call IS the continuation.
So doing something like the following;
Would result in the function taking around 6 seconds to do its “work”, since everything is a continuation of the former.
– this is probably not what you would want.
Instead you can do something like this;
Which would take around 2 seconds.
Using async and await there is something to note in regards to exceptions:
I found this in an MSDN article and I think it explains it pretty well.
Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Exceptions thrown from async void methods can’t be caught naturally.https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
The following code should explain:
So never ever use async void – it will take days to figure out what is actually going on.
If you have any questions please comment below and I will try to update the article with an answer 🙂