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
1 answer

How can I read JSON from a StringContent object in an ApiController?

I'm writing an API controller intended to receive and parse the contents of a JSON asynchronous post, and am unable to read the contents of the StringContent object in that post. Here is the section from my API controller where I expect to see the…
Ken Palmer
  • 2,355
  • 5
  • 37
  • 57
12
votes
4 answers

What's the difference between the following Func> async delegate approaches?

If I have the following method: public async Task DoSomethingAsync(Func> action) { // bunch of async code..then "await action()" } What is the difference between the following two usages: public async Task MethodOneAsync() { …
RPM1984
  • 72,246
  • 58
  • 225
  • 350
12
votes
2 answers

Compile typescript without transpiling async functions

Is there a way to use the TypeScript compiler only to remove type annotations, but not transpiling async functions? Something like a { target: 'esInfinite' } option? The reason is: There are browsers that already support async functions, so I wish…
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
12
votes
3 answers

Is `await` in Python3 Cooperative Multitasking?

I am trying to understand the new asyncio coroutines (introduced in Python 3.5). In 1997 I attended a course at university which roughly covered the content of the book Modern Operating Systems by Andrew Tanenbaum. Somehow the await in Python3…
guettli
  • 25,042
  • 81
  • 346
  • 663
12
votes
1 answer

C# Task returning method in using block

In C# when an Task or Task method is returned from within a using statement is there any risk of the cleanup not properly occurring, or is this a poor practice? What concerns are there as it pertains to the closure of the variable in the using…
David Pine
  • 23,787
  • 10
  • 79
  • 107
12
votes
1 answer

What is the reason behind CS1998 "method lacks await operators"

The C# compiler generates a CS1998 warning when an async method lacks any await operators. What are the reasons behind the warning? I know that async introduces overhead in the method by adding a statemachine and exception handling. Is the primary…
cpt. jazz
  • 1,336
  • 12
  • 21
12
votes
1 answer

How to make AsyncLocal flow to siblings?

This is a very simple example I expect to work but... static AsyncLocal _value = new AsyncLocal(); static void Main(string[] args) { A().Wait(); } static async Task A() { await B(); await…
Vlad
  • 3,001
  • 1
  • 22
  • 52
12
votes
2 answers

Asynchronous map function that await's returns Promise instead of value

I have this code async function addFiles(dir,tree) { return (await readDir(dir)) .map(async (name) => {await readDir(dir); return name;}) } but unfortunately, it just returns a bunch of promises, because there the async function in map is not…
Zane Hitchcox
  • 936
  • 1
  • 9
  • 23
12
votes
3 answers

Why ConfigureAwait(false) does not work while Task.Run() works?

I'm calling an async library method with .ConfigureAwait(false). But, I still end up with deadlock. (I'm using it in ASP.NET controller API) But, if I use the same method wrapped into Task.Run() it works fine. My understanding is, if the libraries…
Krunal Modi
  • 135
  • 1
  • 1
  • 7
12
votes
1 answer

Performance of async in F# vs C# (is there a better way to write async { ... })

FWIW I think that the issues detailed here just comes down to the c# compiler being smarter, and making an efficient state machine based model to handle async code, whereas the F# compiler creates a myriad of objects and function calls that are just…
Paul Westcott
  • 901
  • 1
  • 10
  • 19
12
votes
5 answers

Queue of async tasks with throttling which supports muti-threading

I need to implement a library to request vk.com API. The problem is that API supports only 3 requests per second. I would like to have API asynchronous. Important: API should support safe accessing from multiple threads. My idea is implement some…
STO
  • 10,390
  • 8
  • 32
  • 32
12
votes
2 answers

How can I stop async Process by CancellationToken?

I found beneath code for execute some process without freezing UI. This code is executed when 'Start Work' button is pressed. And I think users would stop this work by 'Stop' button. So I found this article at MSDN..…
youngminz
  • 1,364
  • 2
  • 14
  • 23
12
votes
1 answer

Start a Task and await later and multiple times

In a mobile application I have a potentially long async operation (multiple async network calls grouped in an async function). _myClassField = myClient.DoANumberOfNetworkCallsAsync(); I execute the call right when the app starts, then I show the…
Pinco Pallino
  • 916
  • 1
  • 6
  • 18
12
votes
3 answers

How do I catch thrown errors with async / await?

Here's some code: import 'babel-polyfill' async function helloWorld () { throw new Error ('hi') } helloWorld() I also went deep and tried this as well: import 'babel-polyfill' async function helloWorld () { throw new Error…
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
12
votes
2 answers

Calling an async method using a Task.Run seems wrong?

I recently came across this code written by a contractor we had working for us. It's either devilishly clever or silly (I think the latter but I wanted a second opinion). I'm not massively up to speed on async await. Basically it worked like…
Liam
  • 27,717
  • 28
  • 128
  • 190