We will take a closer look at why we care about async, how it works and then deep dive into async issues.
By the end of this session we will understand what SynchronizationContexts are, when to use ConfigureAwait, how deadlocks occur and how to detect and avoid them. On the way we'll touch on some C#7 features.
Whether you're building web apps or shared libraries, there will be something for everyone.
2. Hi, Iâm Stu
â F# |> I â€
â Developer at
â 8 years of experience in .NET
â Organiser of Bristol F# meetup and DDD South West
â Passionate about Open Source
You can find me at @stuartblang
9. The Bad
âNot clear what is true async
âPerformance overhead
âDuplicated code
âAsync canât go everywhere
âRisk of async deadlocks
âDoing it wrong is much worse that not
doing it at all
17. SynchronizationContext Behaviors
Specific
Thread Used
to Execute
Delegates
Exclusive
(Delegates
Execute One at
a Time)
Ordered
(Delegates
Execute in
Queue Order)
Send May
Invoke
Delegate
Directly
Post May
Invoke
Delegate
Directly
WinForms Yes Yes Yes
If called from
UI thread Never
WPF Yes Yes Yes
If called from
UI thread Never
Default No No No Always Never
ASP.NET No Yes No Always Always
28. Formal definition of async deadlocks
You are susceptible to deadlocks if:
1. You have a current SynchronizationContext that enforces exclusive access;
2. Some code further into your call stack has access to it and can/does:
a. Synchronously block on some async code;
b. Within that async code awaits an incomplete task that does not use
.ConfigureAwait(false), or temporarily removes the context.
If you use .Result, .Wait(), .GetAwaiter().GetResult() you have done a dangerous
thing, and you should be prepared to guard against naughty awaiters (you may not even
control).
29. Resources
Automated Tools
â Microsoft's AsyncPackage (Roslyn Analyzer) -
Async006 - Detects more blocking calls than you
can shake a stick at.
â ConfigureAwait.Fody (yuk)
â ConfigureAwait Checker for ReSharper
â ConfigureAwaitChecker - Roslyn Analyzer + VSIX
â DeadlockDetection
Prevention Methods
â .ConfigureAwait(false) all the things
â ContextFreeTask
â Comment the code
â null the SynchronizationContext (with
handy helper functions)
â async top to bottom (replace our
libraries and framework where we have
to)
â Deadlock detection in QA & Prod
â Detect deadlocks in unit tests?
â Use ASP.NET Core!