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
224
votes
12 answers

Using filesystem in node.js with async / await

I would like to use async/await with some filesystem operations. Normally async/await works fine because I use babel-plugin-syntax-async-functions. But with this code I run into the if case where names is undefined: import fs from 'fs'; async…
Quellenangeber
  • 2,241
  • 2
  • 9
  • 3
221
votes
6 answers

What's the difference between Task.Start/Wait and Async/Await?

I may be missing something but what is the difference between doing: public void MyMethod() { Task t = Task.Factory.StartNew(DoSomethingThatTakesTime); t.Wait(); UpdateLabelToSayItsComplete(); } public async void MyMethod() { var result =…
Jon
  • 38,814
  • 81
  • 233
  • 382
221
votes
3 answers

How do you create an asynchronous method in C#?

Every blog post I've read tells you how to consume an asynchronous method in C#, but for some odd reason never explain how to build your own asynchronous methods to consume. So I have this code right now that consumes my method: private async void…
Khalid Abuhakmeh
  • 10,709
  • 10
  • 52
  • 75
218
votes
10 answers

Simplest async/await example possible in Python

I've read many examples, blog posts, questions/answers about asyncio / async / await in Python 3.5+, many were complex, the simplest I found was probably this one. Still it uses ensure_future, and for learning purposes about asynchronous programming…
Basj
  • 41,386
  • 99
  • 383
  • 673
216
votes
7 answers

Difference between `return await promise` and `return promise`

Given the code samples below, is there any difference in behavior, and, if so, what are those differences? return await promise async function delay1Second() { return (await delay(1000)); } return promise async function delay1Second() { return…
PitaJ
  • 12,969
  • 6
  • 36
  • 55
210
votes
4 answers

Using 'async' in a console application in C#

I have this simple code: public static async Task SumTwoOperationsAsync() { var firstTask = GetOperationOneAsync(); var secondTask = GetOperationTwoAsync(); return await firstTask + await secondTask; } private async Task
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
206
votes
11 answers

Is it possible to await an event instead of another async method?

In my C#/XAML metro app, there's a button which kicks off a long-running process. So, as recommended, I'm using async/await to make sure the UI thread doesn't get blocked: private async void Button_Click_1(object sender, RoutedEventArgs e) { …
Max
  • 9,220
  • 10
  • 51
  • 83
204
votes
2 answers

Await is a reserved word error inside async function

I am struggling to figure out the issue with the following syntax: export const sendVerificationEmail = async () => (dispatch) => { try { dispatch({ type: EMAIL_FETCHING, payload: true }); await Auth.sendEmailVerification(); …
Ilja
  • 44,142
  • 92
  • 275
  • 498
200
votes
8 answers

Suppressing "warning CS4014: Because this call is not awaited, execution of the current method continues..."

This is not a duplicate of "How to safely call an async method in C# without await". How do I nicely suppress the following warning? warning CS4014: Because this call is not awaited, execution of the current method continues before the call is…
noseratio
  • 59,932
  • 34
  • 208
  • 486
198
votes
1 answer

How to get awaitable Thread.Sleep?

I'm writing a network-bound application based on await/sleep paradigm. Sometimes, connection errors happen, and in my experience it pays to wait for some time and then retry operation again. The problem is that if I use Thread.Sleep or another…
Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224
197
votes
11 answers

How can I use Async with ForEach?

Is it possible to use Async when using ForEach? Below is the code I am trying: using (DataContext db = new DataLayer.DataContext()) { db.Groups.ToList().ForEach(i => async { await GetAdminsFromGroup(i.Gid); }); } I am getting the…
James Jeffery
  • 12,093
  • 19
  • 74
  • 108
195
votes
7 answers

How to wait for async method to complete?

I'm writing a WinForms application that transfers data to a USB HID class device. My application uses the excellent Generic HID library v6.0 which can be found here. In a nutshell, when I need to write data to the device, this is the code that…
bmt22033
  • 6,880
  • 14
  • 69
  • 98
191
votes
5 answers

async/await implicitly returns promise?

I read that async functions marked by the async keyword implicitly return a promise: async function getVal(){ return await doSomethingAync(); } var ret = getVal(); console.log(ret); but that is not coherent...assuming doSomethingAsync() returns a…
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
190
votes
5 answers

Async/await vs BackgroundWorker

In the past few days I have tested the new features of .net 4.5 and c# 5. I like its new async/await features. Earlier I had used BackgroundWorker to handle longer processes in the background with responsive UI. My question is: after having these…
Tom
  • 3,899
  • 22
  • 78
  • 137
185
votes
2 answers

Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()

I just saw 3 routines regarding TPL usage which do the same job; here is the code: public static void Main() { Thread.CurrentThread.Name = "Main"; // Create a task and supply a user delegate by using a lambda expression. Task taskA =…
Mou
  • 15,673
  • 43
  • 156
  • 275