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

Architecture for async/await

If you are using async/await at a lower level in your architecture, is it necessary to "bubble up" the async/await calls all the way up, is it inefficient since you are basically creating a new thread for each layer (asynchronously calling an…
valdetero
  • 4,624
  • 1
  • 31
  • 46
59
votes
2 answers

TaskCompletionSource : When to use SetResult() versus TrySetResult(), etc

I'm trying to wrap my head around the TPL, the new async / await features in C# 5, and the mysteries of TaskCompletionSource. One thing that isn't clear to me is when to use SetResult, SetException, and SetCancel versus TrySetResult, TrySetException…
HolySamosa
  • 9,011
  • 14
  • 69
  • 102
58
votes
2 answers

Not much difference between ASP.NET Core sync and async controller actions

I wrote a couple of action methods in a controller to test the difference between sync and async controller actions in ASP.NET core: [Route("api/syncvasync")] public class SyncVAsyncController : Controller { [HttpGet("sync")] public…
Carl Rippon
  • 4,553
  • 8
  • 49
  • 64
58
votes
4 answers

Python [Invalid syntax] with async def

I am trying write discord bots using Python, I have come across and threw together this bot. import discord import asyncio import random client = discord.Client() inEmail = input("Email:") inPassword = input("Passwd:") async def…
Baiqing
  • 1,223
  • 2
  • 9
  • 21
58
votes
2 answers

ES8 Immediately invoked async function expression

I haven't seen these constructs used much but I've found myself writing them to make use of async / await in functions that wouldn't typically return a promise, for example chan.consume(queue, (msg) => { this.pendingMsgs++; // executed…
Drew R
  • 2,988
  • 3
  • 19
  • 27
57
votes
4 answers

for await of VS Promise.all

Is there any difference between this: const promises = await Promise.all(items.map(e => somethingAsync(e))); for (const res of promises) { // do some calculations } And this ? for await (const res of items.map(e => somethingAsync(e))) { // do…
NicoAdrian
  • 946
  • 1
  • 7
  • 18
57
votes
9 answers

async await with setInterval

function first(){ console.log('first') } function second(){ console.log('second') } let interval = async ()=>{ await setInterval(first,2000) await setInterval(second,2000) } interval(); Imagine that I have this code above. When I run it,…
Andrey Radkevich
  • 867
  • 1
  • 9
  • 15
57
votes
3 answers

Using await within a Promise

There seems something inherently wrong with having to define a Promise's callback as asynchronous: return new Promise(async (resolve, reject) => { const value = await somethingAsynchronous(); if (value === something) { return resolve('It…
Druckles
  • 3,161
  • 2
  • 41
  • 65
57
votes
5 answers

Transpile Async Await proposal with Babel.js?

There is a proposal for introducing C# style async-await. I know Babel.js transpiles ES6 to ES5, but is there any way to make it transpile async-await to ES5?
tldr
  • 11,924
  • 15
  • 75
  • 120
57
votes
3 answers

EF Data Context - Async/Await & Multithreading

I frequently use async/await to ensure ASP.NET MVC Web API threads are not blocked by longer-running I/O and network operations, specifically database calls. The System.Data.Entity namespace provides a variety of helper extensions here, such as…
Alex
  • 75,813
  • 86
  • 255
  • 348
57
votes
3 answers

Should we use CancellationToken with MVC/Web API controllers?

There are different examples for async controllers. Some of them use CancellationToken in method definition: public async Task ShowItem(int id, CancellationToken cancellationToken) { await Database.GetItem(id, cancellationToken); …
user1224129
  • 2,759
  • 3
  • 27
  • 29
57
votes
1 answer

Async Void, ASP.Net, and Count of Outstanding Operations

I am trying to understand why an async void method in an ASP.Net application can result in the following exception, while it appears that async Task will not: System.InvalidOperationException: An asynchronous module or handler completed while an…
David Kreps
  • 3,224
  • 4
  • 22
  • 19
56
votes
3 answers

Moq with Task await

Since I have converted my WCF methods to Async, my unit tests have failed, and I can't figure out the correct syntax to get them to work. Cllient proxy class public interface IClientProxy { Task DoSomething(CredentialDataList credentialData,…
jazza1000
  • 4,099
  • 3
  • 44
  • 65
56
votes
3 answers

Waiting for async/await inside a task

I have this construct in my main(), which creates var tasks = new List(); var t = Task.Factory.StartNew( async () => { Foo.Fim(); await Foo.DoBar(); }); //DoBar not completed t.Wait(); //Foo.Fim() done, Foo.DoBar…
Nathan Cooper
  • 6,262
  • 4
  • 36
  • 75
56
votes
4 answers

Node.js vs Async/await in .net

Can someone explain/ redirect me, what is the difference between Node.js's async model(non blocking thread) vs any other language for example c#'s asynchronous way of handling the I/O. This looks to me that both are same model. Kindly suggest.
PKV
  • 773
  • 1
  • 7
  • 17