Damian Hickey

Mostly software and .NET related. Mostly.

An async await anti-pattern - awaiting tasks instead of just returning them.

I've seen this sort of thing being written, especially by people who are new to the async/await features of C#5/.NET4.5, when delegating to an async method, from an async method:

public async Task FooAsync()
{
    await _m.BarAsync();
}

Instead, they should just be writing:

public Task FooAsync()
{
    return _m.BarAsync();
}

The reason is because, in the former, the C# compiler will create a state machine (as viewed with DotPeek), which is simply unnecessary:

The C# compiler is not smart enough to optimize this out.

Edit: Don't do this either, for the reasons stated above:

public async Task<ActionResult> Index()
{ 
    return await Task.FromResult<ActionResult>(View());
}

This should be written as:

public Task<ActionResult> Index()
{ 
    return Task.FromResult<ActionResult>(View());
}

(Thx to @tourismgeek)