7 tips for converting C# code to async/await

Over the past year I’ve moved from working mainly in Java, to working mainly in C#. To be honest, Java and C# have more in common than not, but one of the major differences is async/await. It’s a really powerful tool if used correctly, but also a very quick way to shoot yourself in the foot.

Asynchronous programming looks very similar to synchronous programming. However, there are some core concepts which need to be understood in order to form a proper mental model when converting between synchronous and asynchronous programming patterns.

Here are some of the most common ones I’ve come across.

Naming

Method names must use the suffix Async when returning a Task or Task<T>. Consistency is key as theAsyncsuffix provides not only a mental signal to the caller that the await keyword should be used, but also provides a consistent naming convention.

1// Synchronous method2publicvoidDoSomething(){…}34// Asynchronous method5publicasyncTask DoSomethingAsync(){…}

Return types

Every async method returns a Task. UseTaskwhen there is no specific result for the method, which is synonymous withvoid. UseTask<T>when a return value is required.

1// Original method2publicvoidDoSomething()3{4using(varclient=newHttpClient())5{6client.GetAsync().Result;7}8}910// BAD: This utilizes an anti-pattern. async void provides no mechanism11// for the caller to observe the result, including exceptions.12publicasyncvoidDoSomethingAsync()13{14using(varclient=newHttpClient())15{16awaitclient.GetAsync();17}18}1920// GOOD: This provides proper access to the completion task. The caller may now21// await the method call and observe/handle results and exceptions correctly.22publicasyncTask DoSomethingAsync()23{24using(varclient=newHttpClient())25{26awaitclient.GetAsync();27}28}

Parameters

There is not a way for the compiler to managerefandoutparameters. (That’s a topic for another time.) When multiple values need to be returned you should either use custom objects or aTuple.

1// Original method2publicboolTryGet(stringkey,outstringvalue)3{4value=null;5if(!m_cache.TryGetValue(key,outvalue))6{7value=GetValueFromSource(key);8}910returnvalue!=null;11}1213// New method14publicasyncTask<(boolexists,stringvalue)>TryGetAsync(stringkey)15{16stringvalue=null;17if(!m_cache.TryGetValue(key,outvalue))18{19value=awaitGetValueFromSourceAsync(key);20}2122return(value!=null,value);23}

Delegates

Following up on the lack of thevoidreturn type, no async method should be defined as anActionvariant. When accepting a delegate to an asynchronous method, the asynchronous pattern should be propagated by acceptingFunc<Task>orFunc<Task<T>>.

1publicvoidTraceHelper(Action action)2{3Trace.WriteLine("calling action");4action();5Trace.WriteLine("called action");6}78// Action => Func<Task>9// Action<T> maps to Func<T, Task>10// etc.11publicasyncTask TraceHelperAsync(Func<Task>action)12{13Trace.WriteLine("calling action");14awaitaction();15Trace.WriteLine("called action");16}1718// Example call to the method with a synchronous callback implementation19awaitTraceHelperAsync(()=>{Console.WriteLine("Called me");returnTask.CompletedTask;});

Virtual methods

In asynchronous programming there is no concept of a void return type, as the basis of the model is that each method returns a mechanism for signalling completion of the asynchronous work. When converting base classes which have empty implementations or return constant values, the framework provides methods and helpers to facilitate the pattern.

1// The original synchronous version of the class2publicclassMyClass3{4protectedvirtualvoidDoStuff()5{6// Do nothing7}89protectedvirtualintGetValue()10{11return0;12}13}1415// The converted asynchronous version of the class16publicclassMyClass17{18protectedvirtualTask DoStuffAsync(CancellationToken cancellationToken)19{20// This static accessor avoids new allocations for synchronous 'no-op' methods such as this21returnTask.CompletedTask;22}2324protectedvirtualTask<int>GetValueAsync(CancellationToken cancellationToken)25{26// This factory method returns a completed task with the specified result27returnTask.FromResult(0);28}29}

Interfaces

Like delegates, interfaces should always be declared async which ensures an async-aware model throughout the stack.

1publicinterfaceIMyPlugin2{3Task DoStuffAsync(CancellationToken cancellationToken);4Task<int>DoMoreAsync(CancellationToken cancellationToken);5}67publicclassMyPluginImpl:IMyPlugin8{9// When the method does not have a result, use the static accessor10publicTask DoStuffAsync(CancellationToken cancellationToken)11{12DoSomething();13returnTask.CompletedTask;14}1516// When the method has a result, use the static factory function17publicTask<int>DoMoreAsync(CancellationToken cancellationToken)18{19DoSomething();20returnTask.FromResult(0);21}22}

Mocks

In certain cases, mostly unit test mocks, you may find the need to implement interfaces without having any reason to actually perform any asynchronous calls. In these specific cases it is OK to feign asynchronous execution usingTask.CompletedTaskorTask.FromResult<T>(T result).

1// Example mock implementation for testing. Moq is not smart enough to generate a non-null completed2// task by default, so you will need to explicitly mock out all methods3Mock<IMyPlugin>mockPlugin=newMock<IMyPlugin>();45// When a constant value is returned6mockPlugin.Setup(x=>x.DoStuffAsync(It.IsAny<CancellationToken>()).Returns(Task.CompletedTask);7mockPlugin.Setup(x=>x.DoMoreAsync(It.IsAny<CancellationToken>()).ReturnsAsync(1);89// When a dynamic value is returned10mockPlugin.Setup(x=>x.DoStuffAsync(It.IsAny<CancellationToken>()).Returns(()=>11{12DoStuffImpl();13returnTask.CompletedTask;14});15mockPlugin.Setup(x=>x.DoMoreAsync(It.IsAny<CancellationToken>()).Returns(()=>16{17DoMoreImpl();18returnTask.FromResult(1);19});

Summary

Overall asynchronous programming is much better for performance, but requires a slightly different mental model. I hope these tips help!