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

Asynchronously commit or rollback a transaction scope

As many knows, TransactionScope were forgotten when the async await pattern was introduced in .Net. They were broken if we were trying to use some await call inside a transaction scope. Now this is fixed thanks to a scope constructor option. But it…
Frédéric
  • 9,364
  • 3
  • 62
  • 112
67
votes
2 answers

Await Tasks in Test Setup Code in xUnit.net?

The exact situation is I'm doing E2E tests with Protractor.NET (.NET port of AngularJS's Protractor E2E framework) and I would like to make some web requests (and the API -- System.Net.Http.HttpClient -- has all Async/Task methods) to Arrange my…
Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97
67
votes
3 answers

Throttling asynchronous tasks

I would like to run a bunch of async tasks, with a limit on how many tasks may be pending completion at any given time. Say you have 1000 URLs, and you only want to have 50 requests open at a time; but as soon as one request completes, you open up a…
Josh Wyant
  • 1,177
  • 1
  • 8
  • 13
66
votes
3 answers

How to call an async function?

I want the console to print '1' first, but I am not sure how to call async functions and wait for its execution before going to the next line of code. const request = require("request"); async function getHtml() { await…
chris
  • 2,490
  • 4
  • 32
  • 56
66
votes
5 answers

How to call a generic async method using reflection

public interface IBar { } public class Bar : IBar { } public class Bar2 : IBar { } public interface IFoo { Task Get(T o) where T : IBar; } public class Foo : IFoo { public async Task Get(T o) where T : IBar { ... } } I can…
user2321864
  • 2,207
  • 5
  • 25
  • 35
66
votes
4 answers

Multiple Awaits in a single method

I have a method like this: public static async Task SaveAllAsync() { foreach (var kvp in configurationFileMap) { using (XmlWriter xmlWriter = XmlWriter.Create(kvp.Value, XML_WRITER_SETTINGS)) { FieldInfo[]…
Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
66
votes
4 answers

Unable to declare Interface " async Task MyMethod(Object myObj); "

I'm unable to declare interface IMyInterface { async Task MyMethod(Object myObj); } The compiler tells me: The modifier async isn't valid for this item The async modifier can only be used for methods that have a body Is this…
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
65
votes
7 answers

While loops using Await Async.

This Javascript function seems to use the while loop in an asynchronous way. Is it the correct way to use while loops with asynchronous conditions? var Boo; var Foo = await getBar(i) while(Foo) { Boo = await getBar3(i) if (Boo) { …
65
votes
3 answers

Is it OK to have virtual async method on base class?

I am working with some code, where I have 2 classes with very similar logic and code. I have protected async void LoadDataAsync() method on both classes. Currently I am refactoring it and thinking to move shared logic to base class. Is it OK to have…
Samvel Siradeghyan
  • 3,523
  • 3
  • 30
  • 49
64
votes
8 answers

chrome.runtime.onMessage response with async await

I want to use async await in an onMessage listener: chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{ var key = await getKey(); sendResponse(key); }); However I get undefined when I send a message. From the…
Chris
  • 13,100
  • 23
  • 79
  • 162
64
votes
4 answers

How to use asyncio with existing blocking library?

I have a few blocking functions foo, bar and I can't change those (Some internal library I don't control. Talks to one or more network services). How do I use it as async? E.g. I want to do the following: results = [] for inp in inps: val =…
balki
  • 26,394
  • 30
  • 105
  • 151
64
votes
8 answers

Pattern for calling WCF service using async/await

I generated a proxy with task-based operations. How should this service be invoked properly (disposing of the ServiceClient and the OperationContext afterwards) using async/await? My first attempt was: public async Task
gabrielmaldi
  • 2,157
  • 2
  • 23
  • 39
63
votes
7 answers

Proper request with async/await in Node.JS

In my program I make async call for my function from another API module: var info = await api.MyRequest(value); Module code: var request = require("request") module.exports.MyRequest = async function MyRequest(value) { var options = { …
Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101
63
votes
7 answers

How does C# 5.0's async-await feature differ from the TPL?

I don't see the different between C#'s (and VB's) new async features, and .NET 4.0's Task Parallel Library. Take, for example, Eric Lippert's code from here: async void ArchiveDocuments(List urls) { Task archive = null; for(int i = 0; i…
zildjohn01
  • 11,339
  • 6
  • 52
  • 58
62
votes
4 answers

Is Task.Run considered bad practice in an ASP .NET MVC Web Application?

Background We are currently developing a web application, which relies on ASP .NET MVC 5, Angular.JS 1.4, Web API 2 and Entity Framework 6. For scalability reasons, the web application heavility relies on the async/await pattern. Our domain requires…
Fabe
  • 1,185
  • 4
  • 11
  • 22