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

Properly use Async calls with Angular 5

I have been googling for a few days and found many different scenarios about how to use Async API calls with Angular 5 ( or 2-3-4, whatever ). Can anyone give me some correct example ( some good use-case ) about it? ex. making an API call using (…
bgrujoski
  • 121
  • 1
  • 1
  • 7
11
votes
1 answer

Raising function * into async function *?

Suppose I have a function that takes a generator and returns another generator of the first n elements: const take = function * (n, xs) { console.assert(n >= 0); let i = 0; for (const x of xs) { if (i == n) { break; } yield…
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
11
votes
4 answers

Set ApartmentState for async void main

I have a Windows Forms app. Now I want to use an async method. Since C# 7.1 I can use an async Main method: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1 However, now my STAThread attribute is ignored and my app runs in MTA.…
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189
11
votes
4 answers

Is it legitimate to omit the 'await' in some cases?

I am using async/await in several places in my code. For example, if I have this function: async function func(x) { ... return y; } Then I always call it as follows: async function func2(x) { let y = await func(x); ... } I have…
goodvibration
  • 5,980
  • 4
  • 28
  • 61
11
votes
2 answers

service workers: async await in combination with waituntil is not working properly

i'm struggling with promises in a service worker while using async/await syntax. Following situation: I got a push notification and want to handle the click event. If i use the "old" syntax with then and catch i can iteratore over the list of…
11
votes
2 answers

ASP.NET Webforms with async/await

My Webforms application which is based on .Net 4.6 has to use the async/await-functionality quite extensively. Because I'm quite new to this async/await topic I read quite a lot of best practices like this or this. But I still have some questions…
F. Huber
  • 169
  • 1
  • 2
  • 5
11
votes
3 answers

Using chrome.tabs.executeScript to execute an async function

I have a function I want to execute in the page using chrome.tabs.executeScript, running from a browser action popup. The permissions are set up correctly and it works fine with a synchronous callback: chrome.tabs.executeScript( tab.id, {…
Keith
  • 150,284
  • 78
  • 298
  • 434
11
votes
2 answers

mongoose.connection.collections.collection.drop() throws error every other time

I am setting up testing using Jest for an Node/Express/Mongo project. I have tried to write a function to clear collections so each test starts with a clean slate: const clearCollection = (collectionName, done) => { const collection =…
neurozero
  • 1,036
  • 9
  • 11
11
votes
1 answer

Is there a way to reuse a Job instance?

I'm exploring the use of co-routines in the context of Android UI thread. I implemented contextJob as described in the Coroutines Guide UI. Background work is stared from GUI and I want to re-start it on every click (stop the currently running one…
atok
  • 5,880
  • 3
  • 33
  • 62
11
votes
2 answers

How to properly cancel Task.WhenAll and throw the first exception?

I have multiple tasks that accept a cancellation token and call ThrowIfCancellationRequested accordingly. These tasks will run concurrently using Task.WhenAll. I want all tasks to be cancelled when any tasks throw an exception. I achieved this using…
Rudey
  • 4,717
  • 4
  • 42
  • 84
11
votes
2 answers

Create directory async (without using FileSystemWatcher)?

How can I make make the following code run asynchronously without having to create an extra thread on the thread pool (in other words without Task.Run(...))? Directory.CreateDirectory("\\host\someNetworkDirectory"); Ideally, I would like to use it…
brakeroo
  • 1,407
  • 13
  • 24
11
votes
1 answer

How to find out deadlocking awaited Tasks and their current call stack?

Here is one simplified example I found that really hard to debug deadlock in awaited tasks in some cases: class Program { static void Main(string[] args) { var task = Hang(); task.Wait(); } static async Task Hang() …
bigbearzhu
  • 2,381
  • 6
  • 29
  • 44
11
votes
2 answers

How do I get the new async semantics working in VS2017 RC?

Quoting from Visual Studio 2017 RC Release Notes Language Extensions and Analyzers This release includes some proposed new language extensions that we are working on for the next versions of C# and Visual Basic. These new language features are…
user743382
11
votes
1 answer

Why Elvis (?.) operator doesn't work with async-await?

Let's have a code like this (fragment of App.xaml.xs): public class MethodClass { public async Task Job() { Debug.WriteLine("Doing some sob"); await Task.Delay(1); } } public MethodClass MyClass = null; protected async…
Romasz
  • 29,662
  • 13
  • 79
  • 154
11
votes
1 answer

How to handle async Start() errors in TopShelf

I have a TopShelf service that uses async code to connect to web services and other application servers. If it's unable to initialize its connections on startup, the service should log some errors and gracefully stop. I've had a look at this…
Hydrargyrum
  • 3,378
  • 4
  • 27
  • 41