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
10
votes
2 answers

How does the new async/await feature in C# 5 integrate with the message loop?

I've not had chance to check out the CTP of the new C# async/await feature, but here's something I was wondering: How does it integrate with the message loop? I assume that in a standard Windows application (Winforms, WPF) the continuations are…
Grokys
  • 16,228
  • 14
  • 69
  • 101
10
votes
3 answers

Mutation of captured var in concurrently-executing code

I had an issue in Swift 5.5 and I don't really understand the solution. import Foundation func testAsync() async { var animal = "Dog" DispatchQueue.main.asyncAfter(deadline: .now() + 2) { animal = "Cat" print(animal) …
Jere
  • 103
  • 1
  • 6
10
votes
1 answer

awaiting on future object internals

Having this simple code: import asyncio async def main(): f = asyncio.Future() await f asyncio.run(main()) A coroutine(here main) can await on Future object. It's basically blocked until f either have a result or an exception set, or…
S.B
  • 13,077
  • 10
  • 22
  • 49
10
votes
2 answers

How do I get the "await using" syntax correct?

I have the following synchronous code, which works fine: private void GenerateExportOutput() { using StreamWriter writer = new(Coordinator.OutputDirectory + @"\export.txt"); if (this.WikiPagesToExport.IsEmpty) { …
Bob Vesterman
  • 1,127
  • 1
  • 11
  • 31
10
votes
3 answers

how to access relationships with async sqlalchemy?

import asyncio from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.ext.asyncio import…
muon
  • 12,821
  • 11
  • 69
  • 88
10
votes
1 answer

Update UI after async await call

I load books from API, show activity indicator while loading, update label after server response. activityView.isHidden = false let task = detach { do { let books = try await self.bookService.fetchBooks() …
Ivan Vavilov
  • 1,520
  • 1
  • 15
  • 28
10
votes
1 answer

How to call async functions from VSCode debugger?

If I drop into the VSCode debugger in some javascript code and call an asynchronous function with await it just returns a promise. How can I resolve the promise within the debugger so I can see what the result is? For example, if I define a function…
Alex Long
  • 261
  • 2
  • 5
10
votes
3 answers

How to end Google Speech-to-Text streamingRecognize gracefully and get back the pending text results?

I'd like to be able to end a Google speech-to-text stream (created with streamingRecognize), and get back the pending SR (speech recognition) results. In a nutshell, the relevant Node.js code: // create SR stream const stream =…
noseratio
  • 59,932
  • 34
  • 208
  • 486
10
votes
1 answer

Try-Catch Async Exceptions

This example "fails": static async void Main(string[] args) { try { await TaskEx.Run(() => { throw new Exception("failure"); }); } catch (Exception) { throw new Exception("success"); } } That is, the…
Bent Rasmussen
  • 5,538
  • 9
  • 44
  • 63
10
votes
1 answer

Why does async/await in C# return nullable values even when told not to?

Using C#8, Visual Studio 2019 16.7.2, given the following C# code: #nullable enable public async Task GetStringAsync(); ... public async void Main() { var theString = await GetStringAsync(); ... } Intellisense hovering over…
Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
10
votes
3 answers

How to "multicast" an async iterable?

Can an async generator be somehow broadcast or multicast, so that all its iterators ("consumers"? subscribers?) receive all values? Consider this example: const fetchMock = () => "Example. Imagine real fetch"; async function* gen() { for (let i…
P Varga
  • 19,174
  • 12
  • 70
  • 108
10
votes
1 answer

Does `AsyncLocal` also do the things that `ThreadLocal` does?

I'm struggling to find simple docs of what AsyncLocal does. I've written some tests which I think tell me that the answer is "yes", but it would great if someone could confirm that! (especially since I don't know how to write tests that would…
Brondahl
  • 7,402
  • 5
  • 45
  • 74
10
votes
1 answer

Lock and SemaphoreSlim usage difference with async/await

When accessing critical section in C# with async/await keywords, using lock keyword or Monitor is generally not advised (Why can't I use the 'await' operator within the body of a lock statement?), because it introduces deadlock in the situation…
10
votes
3 answers

Task.WhenAll with Select is a footgun - but why?

Consider: you have a collection of user ids and want to load the details of each user represented by their id from an API. You want to bag up all of those users into some kind of collection and send it back to the calling code. And you want to use…
John Reilly
  • 5,791
  • 5
  • 38
  • 63
10
votes
3 answers

`The 'async' modifier can only be used in TypeScript files.ts(8009)` error when using async in react.js

So when I try to add async/await in the react file, I got this error: The 'async' modifier can only be used in TypeScript files.ts(8009) Does that mean I cannot use async/await in React or that is a problem of vs code or what can I do to enable…
Yingqi
  • 985
  • 2
  • 13
  • 24