Questions tagged [async-await]

This covers the asynchronous programming model supported by various programming languages, using the async and await keywords.

Several programming languages support an asynchronous programming model using co-routines, with the async and await keywords.

Support for the model was added to

  • C# and VB in VS2012
  • Python in 3.5
  • ECMAScript in ECMAScript 2017
  • Rust in 1.39
  • C++ in C++20
  • Swift in Swift 5.5

C# and Visual Studio

Asynchronous programming with async and await was introduced with C# 5.0 in Visual Studio 2012. The run-time support for this language concept is a part of .NET 4.5 / Windows Phone 8 / Windows 8.x Store Runtime.

It's also possible to use async/await and target .NET 4.0 / Windows Phone 7.1 / Silverlight 4 / MonoTouch / MonoDroid / Portable Class Libraries, with Visual Studio 2012+ and Microsoft.Bcl.Async NuGet package, which is licensed for production code.

Async CTP add-on for VS2010 SP1 is also available, but it is not suitable for product development.

Python

Similar syntax was introduced to Python 3.5 (see PEP 492 - Coroutines with async and await syntax.

Previously, it was possible to write co-routines using generators; with the introduction of await and async co-routines were lifted to a native language feature.

C++

Coroutines is introduced in C++20. Using the co_await operator results in suspended execution until resumed. Values can be returned using co_yield and co_return keywords which correspond to suspending and completing execution, respectively.

Swift

The async-await pattern was introduced in Swift 5.5 at WWDC 2021, as part of a broader Swift concurrency initiative. Historically, asynchronous patterns were achieved through the use of Grand Central Dispatch (GCD, ) and “completion handler closure” patterns. The Swift concurrency aims to provide a more intuitive asynchronous coding environment.

ECMAScript

The async and await keywords were first reserved in the ECMAScript 2016 specification and then their use and behavior was fully-specified in the ECMAScript 2017 specification.

Historically, ECMAScript offered “promises”, an improvement over traditional callback patterns, where this sort of looping and exception handling is challenging. Task.js and similar libraries further refined promises, to further simplify the process. But with async functions, all the remaining boilerplate is removed, leaving only the semantically meaningful code in the program text.

Asynchronous vs multi-threaded

The async-await pattern simplifies the writing of asynchronous code. While it is frequently used in multi-threaded environments, it should be noted that “asynchronous” and “multi-threaded” represent two different concepts. The async and await keywords merely allow us to represent relationships and dependencies between asynchronous tasks in a more natural manner, which may be distinct from the mechanism to run code on a different thread. The async-await pattern offers great utility in a multi-threaded environment, but it is not, itself, the multi-threaded mechanism.

Resources:

C#

C++

Swift

Related:

26583 questions
12
votes
2 answers

Multilingual website using OWIN and asynchronous methods

Background I'm creating a simple, multilingual website using ASP.NET 4.6, C#, OWIN pipeline on IIS (Microsoft.Owin.Host.SystemWeb), lots of asynchronous method calls and standard, global resource files (*.resx in App_GlobalResources). The website…
Crozin
  • 43,890
  • 13
  • 88
  • 135
12
votes
3 answers

How to use nested TransactionScopes against an Azure SQL Database

I'm currently trying to use nested transaction scopes for DB access against an Azure SQL Database. I'm using the following code (.Net 4.5.1, my code is async all the way down, it's ASP.Net MVC with EF6.1): public async Task Test() { // In my…
ken2k
  • 48,145
  • 10
  • 116
  • 176
12
votes
2 answers

Async and Await - How is order of execution maintained?

I am actually reading some topics about the Task Parallel Library and the asynchronous programming with async and await. The book "C# 5.0 in a Nutshell" states that when awaiting an expression using the await keyword, the compiler transforms the…
12
votes
1 answer

Sequential version of Task.WhenAll

Is there a nonblocking Task.WaitAll similar to Task.WhenAll, but not parallel? I wrote this, but maybe it’s built-in? public async Task> AwaitAllAsync(IEnumerable> tasks) { List result = new List(); …
Anders
  • 17,306
  • 10
  • 76
  • 144
12
votes
3 answers

Converting loop to tasks

I have the following synchronous code: foreach ( var step in result ) { step.Run(); } I tried to convert it to tasks but I failed to do so. I tried to convert it using Task.WhenAll like this (and I did append async to the method signature): var…
Sascha
  • 10,231
  • 4
  • 41
  • 65
12
votes
1 answer

Windows Service running Async code not waiting on work to complete

In Brief I have a Windows Service that executes several jobs as async Tasks in parallel. However, when the OnStop is called, it seems that these are all immediately terminated instead of being allowed to stop in a more gracious manner. In more…
12
votes
1 answer

How to concat async enumerables?

I have a method with this return type: public async Task> GetAll() It makes some further async calls (unknown number) each of which return a task of enumerable T, and then wants to concat the results for the return. var data1 =…
Vivek
  • 2,103
  • 17
  • 26
12
votes
2 answers

Using async await when implementing a library with both synchronous and asynchronous API for the same functionality

I've got a few questions about how to provide both synchronous and asynchronous implementation of the same functionality in a library. I am gonna ask them first and then provide the example code below (which is actually quite a bit, but in fact it's…
Ceco
  • 1,586
  • 3
  • 16
  • 23
12
votes
4 answers

Asynchronous SHA256 Hashing

I have the following method: public static string Sha256Hash(string input) { if(String.IsNullOrEmpty(input)) return String.Empty; using(HashAlgorithm algorithm = new SHA256CryptoServiceProvider()) { byte[] inputBytes =…
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
12
votes
3 answers

Is there a more readable alternative to calling ConfigureAwait(false) inside an async method?

I'm currently writing a lot of async library code, and I'm aware of the practice of adding ConfigureAwait(false) after each async call so as to avoid marshalling the continuation code back to the original (usually UI) thread context. As I don't like…
Steven Rands
  • 5,160
  • 3
  • 27
  • 56
12
votes
5 answers

How to consume HttpClient from F#?

I'm new to F# and stuck in understanding async in F# from the perspective of a C# developer. Say having the following snippet in C#: var httpClient = new HttpClient(); var response = await…
abatishchev
  • 98,240
  • 88
  • 296
  • 433
12
votes
3 answers

Are a .NET Task thread's resources returned back to the pool temporarily if the thread is waiting on an async operation to finish?

I have a TPL Task that does two things. First, it calls a web service. Second, it inserts some data into a database. I have up to 20 Tasks started at one time doing this same thing over and over again. All they do all day is call web services and…
Trevor
  • 4,620
  • 2
  • 28
  • 37
12
votes
3 answers

Net.HttpClient Cancel ReadAsStringAsync?

I use SendAsync with HttpCompletionOption.ResponseHeadersRead to get the headers first. Next I check the Content-Type and Content-Length to make sure the response is markup and the size is decent. I use a CancellationTokenSource to cancel the…
CodeAngry
  • 12,760
  • 3
  • 50
  • 57
12
votes
2 answers

Difference between ConfigureAwait(false) and omitting await?

You have the following method: async Task DoWorkAsync(); Is there a difference in functionality between the following two invocations: 1. DoWorkAsync(); 2. await DoWorkAsync().ConfigureAwait(false); The only one I see, is that Visual Studio gives…
lekroif
  • 992
  • 3
  • 12
  • 24
12
votes
1 answer

How to deal with side effects produced by async/await when it comes to mutable value types?

Please, consider the following example code: using System.Diagnostics; using System.Threading.Tasks; public struct AStruct { public int Value; public async Task SetValueAsync() { Value = await Task.Run(() => 1); } …
mark
  • 59,016
  • 79
  • 296
  • 580