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?
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:... that gets much hairier with manual continuations.
Additionally,
async
/await
can work with types other thanTask
/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.
I recommend you use
await
rather thanContinueWith
. While - at a high level - they are very similar, they also have different default behavior.When you use
ContinueWith
, you are choosing a lower-level abstraction. In particular, here are some "danger points", and this is why I don't recommend usingContinueWith
unless the method is really simple (or your name is Stephen Toub):async Task
methods are placed on the returned task; exceptions raised from non-async
methods are propagated directly.await
will by default will resume theasync
method in the same "context". This "context" isSynchronizationContext.Current
unless it isnull
, in which case it isTaskScheduler.Current
. This means that if you callMyAsync
on a UI thread (or within an ASP.NET request context), thenMyContinuation
will also execute on the UI thread (or in that same ASP.NET request context). I explain this more on my blog.ContinueWith
; otherwise, it will pick upTaskScheduler.Current
, which can cause surprising behavior. I describe this problem in detail on my blog. That post is aboutStartNew
; butContinueWith
has the same "non-default default scheduler" problem described in that post.await
uses appropriate behavior and optimization flags that are not set by default inContinueWith
. For example, it usesDenyChildAttach
(to ensure asynchronous tasks are not mistakenly used as parallel tasks) andExecuteSynchronously
(an optimization).In short, the only reason to use
ContinueWith
for asynchronous tasks is to save an extremely small amount of time and memory (by avoiding theasync
state machine overhead), and in exchange your code is less readable and maintainable.With an extremely simple example, you might get away with it; but as Jon Skeet pointed out, as soon as you have loops the
ContinueWith
code simply explodes in complexity.