Common async pitfalls—part two
Nov 28, 2020 · 7 minute readFollowing on frompart one, here’s some more of the most common pitfalls I’ve come across—either myself, colleagues and friends, or examples in documentation—and how to avoid them.
‘Fake’-sync is not async
If the method you are calling is synchronous, even in an async method, then call it like any other synchronous method. If you want to yield the thread, then you should useTask.Yieldin most cases. For UI programming, seethis noteaboutTask.Yieldfrom the .NET API documentation.
1publicasyncTask DoStuffAsync(CancellationToken cancellationToken)2{3awaitSomeAsyncMethod(cancellationToken);45// BAD: This provides no benefit and incurs the overhead of a thread hop6awaitTask.Run(()=>7{8SomeSyncMethod();9returnTask.CompletedTask10});1112// GOOD: Just keep the synchronous call on the current thread13SomeSyncMethod();1415// GOOD: If you have a long-running loop, etc, then periodically yield for maximum thread sharing16for(inti=0;i<1000;i++)17{18if(i%100==0)19{20awaitTask.Yield();21}2223// In some cases you will need to do CPU intensive work. This is ok but24// care should be taken to yield at regular intervals25AnExpensiveMethod();26}27}Delegates
Here’s a common pitfall when passing actions as method parameters:
1// A standard method which accepts a callback. The expectation is that2// all methods execute sequentially3publicvoidDoSomething(Action callback)4{5First();67try8{9callback();10}11catch(Exception ex)12{13Trace.WriteException(ex);14}15Second();16}1718// GOOD: Invoked with an explicit action19DoSomething(()=>Console.WriteLine("Hello"));2021// BAD: This delegate is convertible to an async void method, which is allowed to be passed22// to a method which accepts an Action.23DoSomething(async()=>24{25awaitTask.Delay(5000);26// UH-OH! This exception will not be observed by the catch handler in DoSomething above27// since the caller is not aware that this method is asynchronous28thrownewException("This will not be observed");29});The implicit type conversion from the async function toActionis, surprisingly, not a compiler error! This happens because the function doesn’t have a return value, so it’s converted to a method with anasync voidsignature. In this example the side effects aren’t bad, but in a real application this could be terrible as it violates the expected execution contract.
Synchronization
Synchronizing asynchronous code is slightly more complicated than synchronizing synchronous code. Mostly, this is because awaiting a task will result in switching to a different thread. This means that the standard synchronization primitives, which require the same thread to acquire and release a lock, won’t work when used in an async state machine.
Therefore, you must take care to use thread safe synchronization primitives in async methods. For example, usinglock, will block the current thread while your code waits to gain exclusive access. In asynchronous code, threads should only block for a short amount of time.
In general, it’s not a good idea to perform any I/O under a lock. There’s usually a much better way to synchronize access in asynchronous programming.
1privateobject_lock=newobject();23// GOOD: Don't do anything expensive inside a lock4lock(_lock)5{6_cache=newCache();7}89// BAD: This is performing unnecessary I/O under a lock10lock(_lock)11{12_cache=Cache.LoadFromDatabase();13}Lazy Initialization
Imagine you need to lazy initialize some object under a lock.
1privateobject_lock=newobject();2privatebool_initialized=false;3privateint_value;45// BAD: This method performs blocking I/O under a lock6publicvoidInitialize()7{8if(_initialized)9{10return_value;11}1213lock(_lock)14{15if(!_initialized)16{17_value=RetrieveData();18_initialized=true;19}20}2122return_value;23}When convertingRetrieveDatato run asynchronously, you might try to rewriteInitializea few different ways:
1// BAD: Performs I/O and blocks under a lock2lock (_lock)3{4if (!_initialized)5{6_value = RetrieveDataAsync().SyncResult();7_initialized = true;8}9}1011// BAD: Fails at runtime since you cannot change threads under a lock12lock (_lock)13{14if (!_initialized)15{16_value = await RetrieveDataAsync();17_initialized = true;18}19}But there are a few issues:
- You shouldn’t call external code under a lock. The caller has no idea what work the external code will do, or what assumptions it has made.
- You shouldn’t perform I/O under a lock. Code sections under a lock should execute as quickly as possible, to reduce contention with other threads. As soon as you perform I/O under a lock, avoiding contention isn’t possible.
SemaphoreSlim
If you absolutely must perform asynchronous work which limits the number of callers, .NET providesSemaphoreSlimwhich support asynchronous, non-blocking, waiting.
You still need to take care when converting from a synchronous locking construct. Semaphores, unlike monitor locks, aren’t re-entrant.
1private readonly SemaphoreSlim m_gate = new SemaphoreSlim(1, 1);23public async Task DoThingAsync(CancellationToken cancellationToken)4{5// Be careful, semaphores aren't re-entrant!6bool acquired = false;7try8{9acquired = m_gate.WaitAsync(cancellationToken);10if (acquired)11{12// Now that we have entered our mutex it is safe to work on shared data structures13await DoMyCriticalWorkAsync(cancellationToken);14}15}16finally17{18if (acquired)19{20m_gate.Release();21}22}23}IDisposable
IDisposibleis used to finalize acquired resources. In some cases, you need to dispose of these resources asynchronously, to avoid blocking. Unfortunately, you can’t do this insideDispose().
Thankfully, .NET Core 3.0 provides the newIAsyncDisposibleinterface, which allows you to handle asynchronous finalization like so:
1classFoo:IAsyncDisposable2{3publicasyncTask DisposeAsync()4{5awaitSomethingAsync();6}7}89awaitusing(varfoo=newFoo())10{11returnawaitfoo.DoSomethingAsync();12}IEnumerable and IEnumerator
Usually you would implementIEnumerableorIEnumeratorso you can use syntactic sugar, likeforeachand LINQ-to-Objects. Unfortunately, these are synchronous interfaces that can only be used on synchronous data sources. If your underlying data source is actually asynchronous, you shouldn’t expose it using these interfaces, as it will lead to blocking.
With the release of .NET Core 3.0 we got theIAsyncEnumerableandIAsyncEnumeratorinterfaces, which allow you to enumerate asynchronous data sources:
1await foreach(varfooinfooCollection)2{3await foo.DoSomethingAsync();4}Prefer the compiler-generated state machine
There are some valid cases for usingTask.ContinueWith, but it can introduce some subtle bugs if not used carefully. It’s much easier to avoid it, and just useasyncandawaitinstead.
1//BAD:This is using promise-based constructs2public Task DoThingAsync()3{4returnDoMoreThingsAsync().ContinueWith((t)=>DoSomethingElse());5}67//BAD:A much worse version of the above8public Task<int>DoThingAsync()9{10vartcs=new TaskCompletionSource<int>();11DoMoreThingsAsync().ContinueWith(t=>12{13varresult=t.Result;1415//UH-OH!The call to.Result is valid,however,it doesn't properly handle exceptions16//which can lead to an async call chain which never completes.This is an very difficult17//issue to debug as all evidence is garbage collected.18tcs.SetResult(result);19}2021returntcs.Task;22}2324//GOOD:This is using await25public async Task DoThingAsync()26{27await DoMoreThingsAsync();28DoAnotherThing();29}TaskCompletionSource
TaskCompletionSourc<T>allows you to support manual completion in asynchronous code. In general, this class should not be used… but when you have to use it you should be aware of the following behaviour:
1varwaiters=newList<TaskCompletionSource<int>>();23// BAD: This uses default continuation options which result in synchronous callbacks4Task SomeMethod(CancellationToken cancellationToken)5{6vartcs1=newTaskCompletionSource<int>();7waiters.Add(tcs1);8returntcs1.Task;9}1011// GOOD: This uses explicit asynchronous continuations12Task SomeMethod(CancellationToken cancellationToken)13{14vartcs2=newTaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);15waiters.Add(tcs2);16returntcs2.Task;17}1819// The problem comes in when a caller awaits your task. The callee may have an expectation that the callbacks execute20// quickly, but in the example below this is only true for the implementation which specifies asynchronous continuation.21// The reason is the caller of TaskCompletionSource<T>.SetResult will be blocked for the entire duration of the loop22// below when using the first implementation, while in the second implementation the loop will run on a different thread23// and the caller may continue execution quickly as expected.24asyncTask SomeCaller(CancellationToken cancellationToken)25{26varfoo=awaitSomeMethod();27for(inti=0;i<10000;i++)28{29// Do something synchronous and expensive30}31}