Case

So far, I have had plenty of similar snippets:

public async Task<string> GetSomePropertyAsync()
{
    return (await GetAsync()).MyProperty;
}

To prevent additional task creation we can do the following:

public Task<string> GetSomePropertyAsync()
{
    return GetAsync().ContinueWith(task => task.Result.MyProperty);
}

According to this article it is faster.

Another thing - the exception handling in both cases is different - here is a nice post about it.

Trap

So it is worth to get rid of async/await everywhere? Yes, but you should keep in mind some consequences:

public Task Foo()
{
    using (var myDisposable = GetSomeDisposable())
    {
         return DoSomeTask();
    }
}

public async Task Foo()
{
    using (var myDisposable = GetSomeDisposable())
    {
         return await DoSomeTask();
    }
}

In the first case - myDisposable is disposed as soon as the task is created - but no necessarily completed.

In the second snippet - myDisposable is disposed after stuff in DoSomeTask() is completed.


Patryk Wąsiewicz

A very casual blog about programmer's life.