- Don't use .Result or .Wait() - use async/await (unless absolutely necessary - e.g. destructor, domain value factory - see final point)
- Don't used async void - always return a Task
- Always use "ConfigureAwait(false)" inside async library code (unless you need the context) [NB. Not applicable to .NET Core, bear in mind your consumers for .NET Standard]
- Don't throw parameter exceptions in an async method, make the async method private and check the params in a public Task method before calling the private one
- Don't "await Task.FromResult" - remove the async and just return the Task directly (unless async null or type casting).
- When returning Task, don't return "null" - you must return Task.FromResult<T>(null);
- Make sure any function returning Task is suffixed as "Async" to guide the caller
- Don't use parallel for each with async/await, use tasks and Task.WhenAll (unless need custom partitioning)
- Constructors and destructors cannot be marked async, therefore should not call async methods (no compiler warning)
- For ctors - consider making it a factory with CreateInstanceAsync
- For destructors - try to design against it, or fall back to Task.Run().GetAwaiter().GetResult() syntax (see final point)
- When using .Wait() and .Result syntax, ensure it runs on a background thread with no context e.g.
... Task.Run(() => theMainAsync()).GetAwaiter().GetResult();
[Technically GetAwaiter().GetResult() is not for public consumption and should be replaced with .Result, however I prefer it because it unwraps exceptions and it shows that you have purposefully coded as blocking code]
- Published on
Having already been caught out by the ASP.NET deadlock issue when using async code synchronously I did a lot of reading on the subject, from various sources and ended up compiling a list of rules/conventions to follow when dealing with async code.
This is by no means a gospel list and I don't elaborate on why each guideline exists, but it's just a concise set of reminders of things to consider when writing async code, since the compiler will not pick up warnings for a lot of these things.
The list is shared below: