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 the Async suffix 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 method
2public void DoSomething() {  }
3
4// Asynchronous method
5public async Task DoSomethingAsync() {  }

Return types

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

 1// Original method
 2public void DoSomething()
 3{
 4    using (var client = new HttpClient())
 5    {
 6        client.GetAsync().Result;
 7    }
 8}
 9
10// BAD: This utilizes an anti-pattern. async void provides no mechanism
11// for the caller to observe the result, including exceptions.
12public async void DoSomethingAsync()
13{
14    using (var client = new HttpClient())
15    {
16        await client.GetAsync();
17    }
18}
19
20// GOOD: This provides proper access to the completion task. The caller may now
21// await the method call and observe/handle results and exceptions correctly.
22public async Task DoSomethingAsync()
23{
24    using (var client = new HttpClient())
25    {
26        await client.GetAsync();
27    }
28}

Parameters

There is not a way for the compiler to manage ref and out parameters. (That’s a topic for another time.) When multiple values need to be returned you should either use custom objects or a Tuple.

 1// Original method
 2public bool TryGet(string key, out string value)
 3{
 4    value = null;
 5    if (!m_cache.TryGetValue(key, out value))
 6    {
 7        value = GetValueFromSource(key);
 8    }
 9
10    return value != null;
11}
12
13// New method
14public async Task<(bool exists, string value)> TryGetAsync(string key)
15{
16    string value = null;
17    if (!m_cache.TryGetValue(key, out value))
18    {
19        value = await GetValueFromSourceAsync(key);
20    }
21
22    return (value != null, value);
23}

Delegates

Following up on the lack of the void return type, no async method should be defined as an Action variant. When accepting a delegate to an asynchronous method, the asynchronous pattern should be propagated by accepting Func<Task> or Func<Task<T>>.

 1public void TraceHelper(Action action)
 2{
 3    Trace.WriteLine("calling action");
 4    action();
 5    Trace.WriteLine("called action");
 6}
 7
 8// Action => Func<Task>
 9// Action<T> maps to Func<T, Task>
10// etc.
11public async Task TraceHelperAsync(Func<Task> action)
12{
13    Trace.WriteLine("calling action");
14    await action();
15    Trace.WriteLine("called action");
16}
17
18// Example call to the method with a synchronous callback implementation
19await TraceHelperAsync(() => { Console.WriteLine("Called me"); return Task.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 class
 2public class MyClass
 3{
 4    protected virtual void DoStuff()
 5    {
 6        // Do nothing
 7    }
 8
 9    protected virtual int GetValue()
10    {
11        return 0;
12    }
13}
14
15// The converted asynchronous version of the class
16public class MyClass
17{
18    protected virtual Task DoStuffAsync(CancellationToken cancellationToken)
19    {
20        // This static accessor avoids new allocations for synchronous 'no-op' methods such as this
21        return Task.CompletedTask;
22    }
23
24    protected virtual Task<int> GetValueAsync(CancellationToken cancellationToken)
25    {
26        // This factory method returns a completed task with the specified result
27        return Task.FromResult(0);
28    }
29}

Interfaces

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

 1public interface IMyPlugin
 2{
 3    Task DoStuffAsync(CancellationToken cancellationToken);
 4    Task<int> DoMoreAsync(CancellationToken cancellationToken);
 5}
 6
 7public class MyPluginImpl : IMyPlugin
 8{
 9    // When the method does not have a result, use the static accessor
10    public Task DoStuffAsync(CancellationToken cancellationToken)
11    {
12        DoSomething();
13        return Task.CompletedTask;
14    }
15
16    // When the method has a result, use the static factory function
17    public Task<int> DoMoreAsync(CancellationToken cancellationToken)
18    {
19        DoSomething();
20        return Task.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 using Task.CompletedTask or Task.FromResult<T>(T result).

 1// Example mock implementation for testing. Moq is not smart enough to generate a non-null completed
 2// task by default, so you will need to explicitly mock out all methods
 3Mock<IMyPlugin> mockPlugin = new Mock<IMyPlugin>();
 4
 5// When a constant value is returned
 6mockPlugin.Setup(x => x.DoStuffAsync(It.IsAny<CancellationToken>()).Returns(Task.CompletedTask);
 7mockPlugin.Setup(x => x.DoMoreAsync(It.IsAny<CancellationToken>()).ReturnsAsync(1);
 8
 9// When a dynamic value is returned
10mockPlugin.Setup(x => x.DoStuffAsync(It.IsAny<CancellationToken>()).Returns(() =>
11{
12     DoStuffImpl();
13     return Task.CompletedTask;
14});
15mockPlugin.Setup(x => x.DoMoreAsync(It.IsAny<CancellationToken>()).Returns(() =>
16{
17     DoMoreImpl();
18     return Task.FromResult(1);
19});

Summary

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

comments powered by Disqus