Difference between Task and async

C# provides two ways of creating asynchronous methods:

Method 1:

static Task<string> MyAsyncTPL() {
  Task<string> result = PerformWork();
  return result.ContinueWith(t => MyContinuation());
}

Method 2:

static async Task<string> MyAsync() {
  string result = await PerformWork();
  return MyContinuation();
}

Both the above methods are async and achieves the same thing. So, when should I choose one method over the other? Are there any guidelines or advantages of using one over the other?

Jon Skeet
people
quotationmark

await is basically a shorthand for the continuation, by default using the same synchronization context for the continuation.

For very simple examples like yours, there's not much benefit in using await - although the wrapping and unwrapping of exceptions makes for a more consistent approach.

When you've got more complicated code, however, async makes a huge difference. Imagine you wanted:

static async Task<List<string>> MyAsync() {
    List<string> results = new List<string>();
    // One at a time, but each asynchronously...
    for (int i = 0; i < 10; i++) {
        // Or use LINQ, with rather a lot of care :)
        results.Add(await SomeMethodReturningString(i));
    }
    return results;
}

... that gets much hairier with manual continuations.

Additionally, async/await can work with types other than Task/Task<T> so long as they implement the appropriate pattern.

It's worth reading up more about what it's doing behind the scenes. You might want to start with MSDN.

people

See more on this question at Stackoverflow