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

asyncio: RuntimeError this event loop is already running

This seems like a common problem, see for example: RuntimeError: This event loop is already running in python But in my case, I'm only starting the event loop once, at least as far as I can see. Also this example follows directly the instructions…
lhk
  • 27,458
  • 30
  • 122
  • 201
10
votes
2 answers

Trouble with Dart Futures in Flutter : Failed assertion: line 146: '': is not true

I'm building a user authentication module for my app and I am running into trouble with some asynchronous code. Firstly, here is the error that is thrown: E/flutter (17162): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: Unhandled…
jared-nelsen
  • 1,181
  • 5
  • 13
  • 27
10
votes
1 answer

Long running synchronous implementation of an interface that returns a Task

I'm using this question as a basis for my question. TL;DR: If you're not supposed to wrap synchronous code in an async wrapper, how do you deal with long-running, thread-blocking methods that implement an interface method which expects an…
rory.ap
  • 34,009
  • 10
  • 83
  • 174
10
votes
4 answers

How can I handle error 404 in async/await fetch API

Is there any opurtinity to catch Error where there will be no data provided? I recevie Error 404 but can't for example console.log it... class App extends React.Component{ getWeather = async (e) => { e.preventDefault(); const city =…
Paul
  • 296
  • 1
  • 4
  • 16
10
votes
1 answer

Flutter: How can I run a function on background thread in dart

Future getImage() async { var image = await ImagePicker.pickImage(source: ImageSource.camera); setState(() { _image = image; print("IMG:" + _image.toString()); }); setPrefs() ; } Future setPrefs() async { _base64 =…
krishnakumarcn
  • 3,959
  • 6
  • 39
  • 69
10
votes
2 answers

Babel - regeneratorRuntime is not defined, when using transform-async-to-generator plugin

I am not able to setup babel correctly for the usage of async / await. I am using babel 7 and webpack 4. I do not want to use babel-polyfill if possible! My babelrc file: { "presets": [[ "@babel/env", {"modules": false} ]], …
dendog
  • 2,976
  • 5
  • 26
  • 63
10
votes
4 answers

How to WhenAll when some tasks can be null?

I would like to wait all task, but some of them can be null. It is a code like that: Task myTask1 = getData01Async(); Task myTask2 = null; Task myTask3 = null; if(myVariable == true) { myTask2 =…
Álvaro García
  • 18,114
  • 30
  • 102
  • 193
10
votes
4 answers

how to calculate execution time of a async method in c#

So I have a Async method which does something asynchronously. private async static void DoSomethingAsync (int i){} I call it in a loop lets say 50 times. for (int i = 0; i < 50; i++) { DoSomethingAsync (i); } At the end of loop I want to…
ahsant
  • 1,003
  • 4
  • 17
  • 25
10
votes
2 answers

Async function not returning on android

I'm having a problem with an async function not returning when running on android whereas it returns normally when run on iOS. This is the function: _getLocationAsync = async () => { let {status} = await…
A. Wali
  • 454
  • 3
  • 22
10
votes
3 answers

How does await give back control to the event loop during coroutine chaining?

I'm trying my hand at asyncio in Python 3.6 and having a hard time figuring out why this piece of code is behaving the way it is. Example code: import asyncio async def compute_sum(x, y): print("Compute %s + %s ..." % (x, y)) await…
Gaurav Keswani
  • 431
  • 4
  • 14
10
votes
2 answers

How should I convert a function returning a non-generic Task to ValueTask?

I'm working on some code which builds a buffer in memory and then empties it into a TextWriter when the buffer fills up. Most of the time, the character will go straight into the buffer (synchronously) but occasionally (once every 4kb) I need to…
Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
10
votes
1 answer

async / await proper error handling

Assume we have an action that runs on user login (express, node). This is the code that works, written using a lot of callbacks: checkIfEmailAndPasswordAreSet(email, password, (error, response) => { if (error) return errorResponse(403,…
Kasheftin
  • 7,509
  • 11
  • 41
  • 68
10
votes
1 answer

Why does my second snippet of F# async code work, but the first does not?

NB: I am not a professional software developer but I do write a lot of code that doesn't make use of asynchronous anything, so I apologize if this question is really straight forward. I am interfacing with a library written in C#. There is a…
Chechy Levas
  • 2,206
  • 1
  • 13
  • 28
10
votes
5 answers

Unity Coroutine yield return null EQUIVALENT with Task async await

What is the equivalent of yield return null; in Coroutine (that run each frame at Update) in an async method ? The nearest I got to find is await Task.Delay(1);, but it DO NOT run every frame. private IEnumerator RunEachFrame() { while (true) …
Ambroise Rabier
  • 3,636
  • 3
  • 27
  • 38
10
votes
3 answers

Python asyncio/aiohttp: ValueError: too many file descriptors in select() on Windows

Note: Future readers be aware, this question was old, formatted and programmed in a rush. The answer given may be useful, but the question and code probably not. Hello everyone, I'm having trouble understanding asyncio and aiohttp and making both…
Josep
  • 676
  • 2
  • 8
  • 14
1 2 3
99
100