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

How to get the changed state after an async action, using React functional hooks

How to get the changed state after an async action, using React functional hooks? I have found a redux solution for this issue, or a react class component solution, but I am wondering if there is a simple react functional solution. Here is the…
11
votes
3 answers

Does C# await keyword cause the function call to block?

I am trying to grok how async and await works in C#. Consider the two snippets below: var appIdTask = GetAppIdAsync(); var clientSecretTask = GetClientSecretAsync(); var appId = await appIdTask; var clientSecret = await…
ashwnacharya
  • 14,601
  • 23
  • 89
  • 112
11
votes
3 answers

Correct pattern to dispose of cancellation token source

Consider a scenario where you have some asynchronous work to be done and you can run it in a fire and forget mode. This asynchronous work is able to listen for cancellation and so you pass it a cancellation token in order to being able to cancel it.…
11
votes
7 answers

How to block code flow until an event is fired in C#

I have a grid with a button in a WPF application. When the user clicks the button, a method in a utility class is executed which forces the application to receive a click on the grid. The code flow must stop here and not continue until the user has…
Vahid
  • 5,144
  • 13
  • 70
  • 146
11
votes
4 answers

Fire and forget, using Task.Run or just calling an async method without await

In general especially when it comes to libraries or console apps, in order to fire and forget an async method, is it better to just call the async method without awaiting it or use Task.Run? Basically: public static void Main() { // Doing _…
NavidM
  • 1,515
  • 1
  • 16
  • 27
11
votes
1 answer

How to run async function in Airflow?

I am writing a airflow task to read a large csv and save it to postgresql database. I found this asyncpg package that has a copy function which runs much faster than any other packages. However, it is async, and I don't know how to incorporate it…
JOHN
  • 871
  • 1
  • 12
  • 24
11
votes
2 answers

Does await always give other tasks a chance to execute?

I'd like to know what guarantees python gives around when a event loop will switch tasks. As I understand it async / await are significantly different from threads in that the event loop does not switch task based on time slicing, meaning that…
Philip Couling
  • 13,581
  • 5
  • 53
  • 85
11
votes
1 answer

How do I implement an async Drop in Rust?

I have an async fn that returns a type, and want to implement Drop on that type that calls another async function. It's not clear how to do this, and I can't find anything in the docs. The most illuminating article I found is Asynchronous…
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
11
votes
2 answers

How does using await differ from using ContinueWith when processing async tasks?

Here's what I mean: public Task GetSomeObjectByTokenAsync(int id) { string token = repository.GetTokenById(id); if (string.IsNullOrEmpty(token)) { return Task.FromResult(new SomeObject() …
SpiritBob
  • 2,355
  • 3
  • 24
  • 62
11
votes
5 answers

How to implement an efficient WhenEach that streams an IAsyncEnumerable of task results?

I am trying to update my toolset with the new tools offered by C# 8, and one method that seems particularly useful is a version of Task.WhenAll that returns an IAsyncEnumerable. This method should stream the task results as soon as they become…
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
11
votes
2 answers

.Net core & SynchronizationContext & Thread.SetData

From what I know, AspNetCore doesn't have SynchronizationContext . That “re-entering” the request context involves a number of housekeeping tasks, such as setting HttpContext.Current and the current thread’s identity and culture. So I've…
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
11
votes
2 answers

Unhandled promise rejection. This error originated either by throwing inside of an async function - NodeJS

I'm very new with NodeJS. I'm trying to create a simple server that has a connection to my mongoDB Atlas database but when I run my server I get this error: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated…
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
11
votes
2 answers

How to run an Asyncio task without awaiting?

I need to call a task periodically but (a)waiting times are almost more than the period. In the following code, How can I run do_something() task without need to await for the result? import asyncio import time from random import randint …
Ario
  • 549
  • 1
  • 8
  • 18
11
votes
1 answer

Returning value from normal function which called suspend function using Kotlin Coroutine

Hi I am using Kotlin coroutine library in a project. The below method calls a suspend function which return a boolean value. fun isNetworkAvailable(context: Context?): Boolean { //return checkNetworkReachability(context) var…
11
votes
4 answers

How to make Dispose await for all async methods?

I have disposable class with async methods. class Gateway : IDisposable { public Gateway() {} public void Dispose() {} public async Task Request1 () {...} public async Task Request2 () {...} public async Task Request3 ()…
Denis535
  • 3,407
  • 4
  • 25
  • 36