Common async pitfalls—part one
Nov 17, 2020 · 8 minute readThe .NET Framework provides a great programming model that enables high performance code using an easy to understand syntax. However, this can often give developers a false sense of security, and the language and runtime aren’t without pitfalls. Ideally static analysers, like theMicrosoft.VisualStudio.Threading.Analyzers Roslyn analysers, would catch all these issues at build time. While they do help catch a lot of mistakes, they can’t catch everything, so it’s important to understand the problems and how to avoid them.
Here’s a collection of some of the most common pitfalls I’ve come across—either myself, colleagues and friends, or examples in documentation—and how to avoid them.
Blocking calls
The main benefit of asynchronous programming is that the thread pool can be smaller than a synchronous application while performing the same amount of work. However, once a piece of code begins to block threads, the resulting thread pool starvation can be ugly.
1publicasyncTask DoStuffAsync(CancellationToken cancellationToken)2{3Task<bool>resultTask=StuffAsync(cancellationToken);45// BAD: These may deadlock depending on thread pool capacity or the presence of a sync context6resultTask.Wait();7resultTask.Result;8resultTask.GetAwaiter().GetResult();910// BAD: This blocks the thread11Thread.Sleep(5000);1213// GOOD: Always await14awaitresultTask;1516// GOOD: This does not block and allows for maximum throughput17awaitTask.Delay(5000,cancellationToken);18}If I run a small test, which makes 5000 concurrent HTTP requests to a local server, there are dramatically different results depending on how many blocking calls are used.
% blocking shows the number of calls that useTask.Result, which blocks the thread. All other requests useawait.
| % Blocking | Threads | Total Duration | Avg. Duration |
|---|---|---|---|
| 0 | 24 | 00:00:11.961 | 0.0023923 |
| 5 | 268 | 00:02:16.574 | 0.0273148 |
The increased total duration when using blocking calls is due to the thread pool growth, which happens slowly. You can always tune the thread pool settings to achieve better performance, but it will never match the performance you can achieve with non-blocking calls.
Streams
Like all other blocking calls, any methods fromSystem.IO.Streamshould use their async equivalents:ReadtoReadAsync,WritetoWriteAsync,FlushtoFlushAsync, etc. Also, after writing to a stream, you should call theFlushAsyncmethod before disposing the stream. If not, theDisposemethod may perform some blocking calls.
CancellationToken
You should always propagate cancellation tokens to the next caller in the chain. This is called a cooperative cancellation model. If not, you can end up with methods that run longer than expected, or even worse, never complete.
To indicate to the caller that cancellation is supported, the final parameter in the method signature should be aCancellationTokenobject.
1publicasyncTask DoStuffAsync()2{3// BAD: This method does not accept a cancellation token. Cooperative cancellation is extremely important.4awaitStuffAsync();5}67publicasyncTask DoStuffAsync(CancellationToken cancellationToken)8{9varhttpClient=newHttpClient();1011// BAD: The caller has provided a cancellation token for cooperative cancellation but it was not provided12// downstream. Regardless of the token being signaled the http client will not return until the13// operation completes.14awaithttpClient.GetAsync("http://example.com");1516// GOOD: Always propagate the token to the next caller in the chain17awaithttpClient.GetAsync("http://example.com",cancellationToken);18}Linked tokens
If you need to put a timeout on an inner method call, you can link one cancellation token to another. For example, you want to make a service-to-service call, and you want to enforce a timeout, while still respecting the external cancellation.
1publicasyncTask<int>DoThingAsync(CancellationToken cancellationToken)2{3using(varcancelTokenSource=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))4{5// The cancellation token source will now manage a timer which automatically notifies the parent6// token.7cancelTokenSource.CancelAfter(TimeSpan.FromSeconds(10));89// By linking the token source we will now cooperatively cancel. We have also10// provided a time based auto-cancellation signal which only applies to the11// the single method. This is how nested cancellation scopes may be used in circuit breakers.12awaitGetAsync(cancelTokenSource.Token);13}1415// Other calls within the method may not need this restricted timeout so the original16// cancellation token is used instead.17awaitDoOtherThingAsync(cancellationToken);18}Cancelling uncancellable operations
Sometimes you may find the need to call an API which does not accept a cancellation token, but your API receives a token and is expected to respect cancellation. In this case the typical pattern involves managing two tasks and effectively abandoning the un-cancellable operation after the token signals.
1publicasyncTask<int>DoThingAsync(CancellationToken cancellationToken)2{3vartcs=newTaskCompetionSource<int>();4using(varregistration=cancellationToken.Register(()=>tcs.SetResult(0)))5{6varcompletedTask=awaitTask.WhenAny(tcs.Task,DoNonCancellableCallAsync());7if(completedTask==tcs.Task)8{9// We have been cancelled, so take appropriate action here. At this point in time the non-cancellable call is10// still running. Once it completes everything will be properly garbage collected11thrownewOperationCanceledException(cancellationToken);12}1314returnawaitcompletedTask;15}16}Constructors
Occasionally, you may find yourself wanting to perform asynchronous work during initialization of a class instance. Unfortunately, there is no way to make constructors async.
1publicclassFoo2{3publicFoo(inta,intc)4{5_a=a;6// DON'T DO THIS!7_b=CallSomethingAsync().SyncResult();8_c=c;9}1011privatereadonlyint_a;12privatereadonlystring_b;13privatereadonlyint_c;14}There are a couple of different ways to solve this. Here’s a pattern I like:
- A public static creator method, which publicly replaces the constructor
- A private async member method, which does the work the constructor used to do
- A private constructor, so callers can’t directly instantiate the class by mistake
So, if I apply the same pattern to the class above the class becomes:
1publicclassFoo2{3publicstaticasyncTask<Foo>CreateAsync(inta,intc)4{5Foo instance=newFoo(a,c);6awaitinstance.InitializeAsync();7returninstance;8}910privateFoo(inta,intc)11{12// GOOD: readonly keyword is retained13_a=a;14_c=c;15}1617privateasyncTask InitializeAsync()18{19// GOOD: all async work is performed here20// NOTE: make sure initialization order is correct when porting existing code21_b=awaitCallSomethingAsync();22}2324privatereadonlyint_a;25privatereadonlyint_c;2627string_b;28}And we can instantiate the class by callingvar foo = await Foo.CreateAsync(1, 2);.
In cases where the class is part of an inheritance hierarchy, the constructor can be made protected andInitializeAsynccan be made protected virtual, so it can be overridden and called from derived classes. Each derived class will need to have its ownCreateAsyncmethod.
Parallelism
Avoid premature optimization
It might be very tempting to try to perform parallel work by not immediately awaiting tasks. In some cases, you can make significant performance improvements. However, if not used with care you can end up in debugging hell involving socket or port exhaustion, or database connection pool saturation.
1publicasyncTask DoTwoThingsAsync(CancellationToken cancellationToken)2{3// Depending on what you are doing under the covers, this may cause unintended4// consequences such as exhaustion of outgoing sockets or database connections.5varthing1Task=FirstAsync(cancellationToken);6varthing2Task=SecondAsync(cancellationToken);7awaitTask.WhenAll(thing1Task,thing2Task);89// Prefer sequential execution of asynchronous calls10awaitFirstAsync(cancellationToken);11awaitSecondAsync(cancellationToken);12}Using async everywhere generally pays off without having to make any individual piece of code faster via parallelization. When threads aren’t blocking you can achieve higher performance with the same amount of CPU.
Avoid Task.Factory.StartNew, and use Task.Run only when needed
Even in the cases where not immediately awaiting is safe, you should avoidTask.Factory.StartNew, and only useTask.Runwhen you need to run some CPU-bound code asynchronously.
The main wayTask.Factory.StartNewis dangerous is that it can look like tasks are awaited when they aren’t. For example, if youasync-ify the following code:
1Task.WhenAll(Task.Factory.StartNew(Foo),Task.Factory.StartNew(Foo2)).Wait();be careful because changing the delegate to one that returnsTask,Task.Factory.StartNewwill now returnTask<Task>. Awaiting only the outer task will only wait until the actual task starts, not finishes.
1// BAD: Only waits until all tasks have been scheduled, not until the actual work has completed2awaitTask.WhenAll(Task.Factory.StartNew(FooAsync),Task.Factory.StartNew(Foo2Async));Normally what you want to do, when you know delegates are not CPU-bound, is to just use the delegates themselves. This is almost always the right thing to do.
1// GOOD: Will wait until the tasks have all completed2awaitTask.WhenAll(FooAsync(),Foo2Async());However, if you are certain the delegates are CPU-bound, and you want to offload this to the thread pool, you can useTask.Run. It’s designed to support async delegates. I’d still recommend readingTask.Run Etiquette and Proper Usagefor a more thorough explanation.
12// Ok if FooAsync is known to be primarily CPU-bound (especially before going async).3// Will schedule the CPU-bound work like Task.Factory.StartNew does,4// and automatically convert Task<Task> into a 'proxy' Task that represents the actual work5awaitTask.WhenAll(Task.Run(FooAsync),Task.Run(Foo2Async))If, for some extremely unlikely reason, you really do need to useTask.Factory.StartNewyou can useUnwrap()orawait awaitto convert aTask<Task>into aTaskthat represents the actual work. I’d recommend readingTask.Run vs Task.Factory.StartNewfor a deeper dive into the topic.
Null conditionals
Using the null conditional operator with awaitables can be dangerous. Awaiting null throws aNullReferenceException.
1// BAD: Will throw NullReferenceException if foo is null2awaitfoo?.DoStuffAsync()Instead, you must do a manual check first.
1// GOOD2if(foo!=null)3{4awaitfoo.DoStuffAsync();5}ANull-conditional awaitis currently under consideration for future versions of C#, but until then you’re stuck with manually checking.