Alex Rivera | Logout

What's the difference between returning void and returning a Task?

Asked 2011-11-07T22:07:55.073
147

In looking at various C# Async CTP samples I see some async functions that return void, and others that return the non-generic Task. I can see why returning a Task<MyType> is useful to return data to the caller when the async operation completes, but the functions that I've seen that have a return type of Task never return any data. Why not return void?

Edit
Report

1 Answer

25

Methods returning Task and Task<T> are composable - meaning that you can await them inside of an async method.

async methods returning void are not composable, but they do have two other important properties:

  1. They can be used as event handlers.
  2. They represent a "top-level" asynchronous operation.

The second point is important when you're dealing with a context that maintains a count of outstanding asynchronous operations.

The ASP.NET context is one such context; if you use async Task methods without awaiting them from an async void method, then the ASP.NET request will be completed too early.

Another context is the AsyncContext I wrote for unit testing (available here) - the AsyncContext.Run method tracks the outstanding operation count and returns when it's zero.

answered 2011-11-09T01:46:07.680

Your Answer