← All Articles
var taskList = new List<Task>();
a) taskList.Add(SampleAsyncMethod());
vs.
b) await SampleAsyncMethod();

I recently had a discussion with a developer about when to use one vs. the other and it's not the first time I've had the conversation. The reasons you might want to use one over the other can be conditional based on what you are trying to do, but for my purposes here, I want to go over what each will do so that as a developer you can select the right one for the right situation.

As a rule, async is what it sounds like, a method that can run on the thread independent of other processes. Normally, C# is synchronous, meaning, it's running on a single thread and work has to complete before the next task can be run. The TPL (Task Parallel Library) and the async/await pattern gives you an alternative coding paradigm.

For method a) above, the inferred function definition would be:

private async Task<string> SampleAsyncMethod() {
    return "hello world";
}

So when we run sample a, var ends up containing a type Task. In order to run that task we would need to do a Task.WaitAll(taskList.ToArray());, which is blocking. Waits until all tasks are complete before continuing.

Or await Task.WhenAll(taskList.ToArray());, which is non-blocking and creates a task to run all tasks.

Depending on how you wanted the tasks to execute.

If we added the "await" keyword to the invocation of the method such as await SampleAsyncMethod() we would fire off a task and continue to process until we hit something which required us to wait for the result of the awaited call. With this pattern, we can speed up the single threaded code block and make it much for efficient.