How to cancel a Task in await?

Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken with async methods. To summarize, you pass a CancellationToken into each method that supports cancellation, and that method must check it periodically. private async Task TryTask() … Read more

WaitAll vs WhenAll

Task.WaitAll blocks the current thread until everything has completed. Task.WhenAll returns a task which represents the action of waiting until everything has completed. That means that from an async method, you can use: await Task.WhenAll(tasks); … which means your method will continue when everything’s completed, but you won’t tie up a thread to just hang … Read more

Best practice to call ConfigureAwait for all server-side code

Update: ASP.NET Core does not have a SynchronizationContext. If you are on ASP.NET Core, it does not matter whether you use ConfigureAwait(false) or not. For ASP.NET “Full” or “Classic” or whatever, the rest of this answer still applies. Original post (for non-Core ASP.NET): This video by the ASP.NET team has the best information on using … Read more

Parallel foreach with asynchronous lambda

If you just want simple parallelism, you can do this: var bag = new ConcurrentBag<object>(); var tasks = myCollection.Select(async item => { // some pre stuff var response = await GetData(item); bag.Add(response); // some post stuff }); await Task.WhenAll(tasks); var count = bag.Count; If you need something more complex, check out Stephen Toub’s ForEachAsync post.