C# – Efficient mixing of sync and async methods within a single method

asynchronous-programmingc

Okay, it sounds odd, but the code is very simple and explains the situation well.

public virtual async Task RemoveFromRoleAsync(AzureTableUser user, string role)
{
    AssertNotDisposed();
    var roles = await GetRolesForUser(user);
    roles.Roles = RemoveRoles(roles.Roles, role);
    await Run(TableOperation.Replace(roles));
}

(I know I'm talking kind of in the abstract below, but the above is an actual method from what will be actual production code that is actually doing what I'm asking about here, and I'm actually interested in your actually reviewing it for correctness vis a vis the async/await pattern.)

I'm encountering this pattern more and more often now that I'm using async/await more. The pattern consists of the following chain of events:

  1. Await an initial call that gets me some information I need to work on
  2. Work on that information synchronously
  3. Await a final call that saves the updated work

The above code block is typically how I go about handling these methods. I await the first call, which I have to because it is asynchronous. Next, I do the work that I need to do which isn't IO or resource bound, and so isn't async. Finally, I save my work which is also an async call, and out of cargo-cult I await it.

But is this the most efficient/correct way to handle this pattern? It seems to me I could skip awaiting the last call, but what if it fails? And should I use a Task method such as ContinueWith to chain my synchronous work with the original call? I'm just at a point right now where I'm not sure if I'm handling this correctly.

Given the code in the example, is there a better way to handle this async/sync/async method call chain?

Best Answer

Yes, I think this is the right way to do it.

You can't skip the second await. If you did, the method would seem to complete too early (before the removal was actually done), and you would never find out if the removal failed.

I don't see how would ContinueWith() or anything like that help here. You could use it to avoid using await, but it would make your code more complicated and less readable. And that's the whole point of await: making writing asynchronous code simpler, when compared with using continuations.