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
92
votes
5 answers

How to dispose TransactionScope in cancelable async/await?

I'm trying to use the new async/await feature to asynchronously work with a DB. As some of the requests can be lengthy, I want to be able to cancel them. The issue I'm running into is that TransactionScope apparently has a thread affinity, and it…
chase
  • 1,623
  • 1
  • 16
  • 21
91
votes
4 answers

How do I handle async operations in Startup.Configure?

In my ASP.NET 5 app, I want to load some data from Azure into a cache inside my Startup.Configure method. The Azure SDK exposes async methods exclusively. Typically, calling an async method is done via await inside an async method, like this: public…
DevHawk
  • 995
  • 1
  • 7
  • 6
91
votes
3 answers

Why can't "async void" unit tests be recognized?

async void unit tests cannot be run within Visual Studio 2012: [TestClass] public class MyTestClass { [TestMethod] public async void InvisibleMyTestMethod() { await Task.Delay(1000); Assert.IsTrue(true); } } If I…
Max
  • 3,453
  • 3
  • 32
  • 50
89
votes
9 answers

Await a Async Void method call for unit testing

I have a method that looks like this: private async void DoStuff(long idToLookUp) { IOrder order = await orderService.LookUpIdAsync(idToLookUp); // Close the search IsSearchShowing = false; } //Other stuff in case you want to…
Vaccano
  • 78,325
  • 149
  • 468
  • 850
89
votes
5 answers

Non-Generic TaskCompletionSource or alternative

I'm working with an alert window (Telerik WPF) that is normally displayed asynchronously ( code continues running while it is open) and I want to make it synchronous by using async/await. I have this working with TaskCompletionSource but that class…
Kevin Kalitowski
  • 6,829
  • 4
  • 36
  • 52
88
votes
6 answers

async/await inside arrow functions (Array#map/filter)

I'm getting compile time error in this code: const someFunction = async (myArray) => { return myArray.map(myValue => { return { id: "my_id", myValue: await service.getByValue(myValue); } }); }; Error…
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
88
votes
2 answers

Why would I bother to use Task.ConfigureAwait(continueOnCapturedContext: false);

Consider the following code of windows forms: private async void UpdateUIControlClicked(object sender, EventArgs e) { this.txtUIControl.Text = "I will be updated after await - i hope!"; await…
Yawar Murtaza
  • 3,655
  • 5
  • 34
  • 40
87
votes
9 answers

Await in catch block

I have the following code: WebClient wc = new WebClient(); string result; try { result = await wc.DownloadStringTaskAsync( new Uri( "http://badurl" ) ); } catch { result = await wc.DownloadStringTaskAsync( new Uri( "http://fallbackurl" )…
György Balássy
  • 2,938
  • 1
  • 28
  • 23
86
votes
6 answers

How can I prevent synchronous continuations on a Task?

I have some library (socket networking) code that provides a Task-based API for pending responses to requests, based on TaskCompletionSource. However, there's an annoyance in the TPL in that it seems to be impossible to prevent synchronous…
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
85
votes
2 answers

Is Async await keyword equivalent to a ContinueWith lambda?

Could someone please be kind enough to confirm if I have understood the Async await keyword correctly? (Using version 3 of the CTP) Thus far I have worked out that inserting the await keyword prior to a method call essentially does 2 things, A. It…
Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243
85
votes
1 answer

Using asyncio.Queue for producer-consumer flow

I'm confused about how to use asyncio.Queue for a particular producer-consumer pattern in which both the producer and consumer operate concurrently and independently. First, consider this example, which closely follows that from the docs for…
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
85
votes
5 answers

Correct way to get the CoreDispatcher in a Windows Store app

I'm building a Windows Store app, and I have some code that needs to be posted to the UI thread. For that, i'd like to retrieve the CoreDispatcher and use it to post the code. It seems that there are a few ways to do so: // First…
lysergic-acid
  • 19,570
  • 21
  • 109
  • 218
85
votes
13 answers

How to 'await' raising an EventHandler event

Sometimes the event pattern is used to raise events in MVVM applications by or a child viewmodel to send a message to its parent viewmodel in a loosely coupled way like this. Parent ViewModel searchWidgetViewModel.SearchRequest += (s,e) => { …
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
83
votes
5 answers

What's the new C# await feature do?

Can anyone explain what the await function does?
Chris Nicol
  • 10,256
  • 7
  • 39
  • 49
83
votes
2 answers

What is the difference between await Task and Task.Result?

public async Task GetName(int id) { Task nameTask = Task.Factory.StartNew(() => string.Format("Name matching id {0} = Developer", id)); return nameTask.Result; } In above method return statement I am using the Task.Result…
Yawar Murtaza
  • 3,655
  • 5
  • 34
  • 40