Introducing Task.CompletedTask

Tags: C#, async, Task

When you start asynchronous programming with the async/await keywords, there are several rules you should always think about:

  • Avoid async void
  • Do not return null instead of a Task
  • Await your async methods
  • Know your synchronization context (ConfigureAwait)

Back in the days I’ve written about my “Empty” helper class to ensure my team didn’t return null. Recently in Visual Studio I noticed that Task had a CompletedTask property. Browsing through the documents on MSDN, I noticed this property was added in .NET 4.6 to achieve the same job: returning a completed task. So what should you use?

Whenever you’re in need of returning a Task object, but have no asnyc method to return, use Task.CompletedTask. This also counts for virtual async methods without implementation:

public virtual Task LoadDataAsync(string deepLink, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
{
    return Task.CompletedTask; // null would throw exception on await
}

If you’re in need of a Task<T> object or trying to return another object, use Task.FromResult.

Comments

comments powered by Disqus