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
77
votes
3 answers

Why ConfigureAwait(false) is not the default option?

As you know, it it a good idea to call Task.ConfigureAwait(false) when you are waiting on a task in a code that does not need to capture a synchronization context, because it can cause deadlocks otherwise. Well, how often do you need to capture a…
RX_DID_RX
  • 4,113
  • 4
  • 17
  • 27
76
votes
3 answers

How to reset a CancellationToken properly?

I have been playing round with the Async CTP this morning and have a simple program with a button and a label. Click the button and it starts updating the label, stop the button it stops writing to the label. However, I'm not sure how to reset the…
76
votes
4 answers

Does C# perform short circuit evaluation of if statements with await?

I believe that C# stops evaluating an if statement condition as soon as it is able to tell the outcome. So for example: if ( (1 < 0) && check_something_else() ) // this will not be called Since the condition (1 < 0) evaluates as false, the &&…
Aidan
  • 4,783
  • 5
  • 34
  • 58
76
votes
2 answers

Flutter, render widget after async call

I would like to render a widget that needs an HTTP call to gather some data. Got the following code (simplified) import 'package:flutter/material.dart'; import 'dart:async'; import 'dart:convert'; void main() { runApp(new MyApp()); } class MyApp…
Alexi Coard
  • 7,106
  • 12
  • 38
  • 58
76
votes
7 answers

How run async / await in parallel in Javascript

Finally async/await will be supported in all major browser soon except IE. So now we can start writing more readable code with async/await but there is a catch. A lot of people use async await like this: const userResponse = await…
NoNameProvided
  • 8,608
  • 9
  • 40
  • 68
76
votes
4 answers

(ES6) class (ES2017) async / await getter

Is it or will it be possible to have an ES6 class getter return a value from an ES2017 await / async function. class Foo { async get bar() { var result = await someAsyncOperation(); return result; } } function…
Enki
  • 1,565
  • 2
  • 13
  • 20
76
votes
3 answers

Difference between the TPL & async/await (Thread handling)

Trying to understanding the difference between the TPL & async/await when it comes to thread creation. I believe the TPL (TaskFactory.StartNew) works similar to ThreadPool.QueueUserWorkItem in that it queues up work on a thread in the thread…
coding4fun
  • 8,038
  • 13
  • 58
  • 85
75
votes
6 answers

How to write an "awaitable" method?

I'm finally looking into the async & await keywords, which I kind of "get", but all the examples I've seen call async methods in the .Net framework, e.g. this one, which calls HttpClient.GetStringAsync(). What I'm not so clear on is what goes on in…
Andrew Stephens
  • 9,413
  • 6
  • 76
  • 152
74
votes
5 answers

In JavaScript how do I/should I use async/await with XMLHttpRequest?

Full disclosure: I'd qualify myself as having intermediate JavaScript knowledge. So this is slightly above my experience level at this time. I've got a Google Chrome Extension that does an AJAX request for a local file:/// as soon as a page loads.…
jkupczak
  • 2,891
  • 8
  • 33
  • 55
74
votes
3 answers

How do I get a return value from Task.WaitAll() in a console app?

I am using a console app as a proof of concept and new need to get an async return value. I figured out that I need to use Task.WaitAll() in my main method to avoid needing an async "main()" method, which is illegal. I'm now stuck trying to figure…
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
74
votes
2 answers

can not await async lambda

Consider this, Task task = new Task (async () =>{ await TaskEx.Delay(1000); }); task.Start(); task.Wait(); The call task.Wait() does not wait for the task completion and the next line is executed immediately, but if I wrap the async lambda…
kennyzx
  • 12,845
  • 6
  • 39
  • 83
73
votes
6 answers

Why no-return-await vs const x = await?

What is the difference between return await foo() and const t = await foo(); return t http://eslint.org/docs/rules/no-return-await
AturSams
  • 7,568
  • 18
  • 64
  • 98
73
votes
5 answers

async/await always returns promise

I'm trying async/await functionality. I have such code imitating a request: const getJSON = async () => { const request = () => new Promise((resolve, reject) => ( setTimeout(() => resolve({ foo: 'bar'}), 2000) )); const json = await…
user3309314
  • 2,453
  • 2
  • 17
  • 30
73
votes
5 answers

Executing tasks in parallel

Ok, so basically I have a bunch of tasks (10) and I want to start them all at the same time and wait for them to complete. When completed I want to execute other tasks. I read a bunch of resources about this but I can't get it right for my…
Yann Thibodeau
  • 1,111
  • 1
  • 12
  • 20
73
votes
3 answers

How do the semantics of AsyncLocal differ from the logical call context?

.NET 4.6 introduces the AsyncLocal class for flowing ambient data along the asynchronous flow of control. I've previously used CallContext.LogicalGet/SetData for this purpose, and I'm wondering if and in what ways the two are semantically…
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152