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
62
votes
4 answers

CancellationToken with async Dapper methods?

I'm using Dapper 1.31 from Nuget. I have this very simple code snippet, string connString = ""; string query = ""; int val = 0; CancellationTokenSource tokenSource = new CancellationTokenSource(); using (IDbConnection conn = new…
Pedigree
  • 2,384
  • 3
  • 23
  • 28
61
votes
2 answers

Error: "Cannot use 'async' on methods without bodies". How to force async child overrides?

I'm working on a system in which multiple client objects are expected to implement a particular function via an interface, and I want that function to run asynchronously with continuations (I'm expecting the implementations to be I/O-bound and want…
Lars Kemmann
  • 5,509
  • 3
  • 35
  • 67
61
votes
1 answer

What does the "yield from" syntax do in asyncio and how is it different from "await"

From the perspective of someone who has written asyncio code but is looking to better understand the inner workings, what is yield from, await and how are those useful for allowing asynchronous code? There is one highly upvoted question asking about…
Azsgy
  • 3,139
  • 2
  • 29
  • 40
61
votes
3 answers

Fire and forget async method in ASP.NET MVC

The general answers such as here and here to fire-and-forget questions is not to use async/await, but to use Task.Run or TaskFactory.StartNew passing in the synchronous method instead. However, sometimes the method that I want to fire-and-forget is…
acarlon
  • 16,764
  • 7
  • 75
  • 94
61
votes
4 answers

What are the differences between using ConfigureAwait(false) and Task.Run?

I understand that it's recommended to use ConfigureAwait(false) for awaits in library code so that subsequent code does not run in the caller's execution context, which could be a UI thread. I also understand that await Task.Run(CpuBoundWork) should…
Sam
  • 40,644
  • 36
  • 176
  • 219
60
votes
1 answer

Is it safe to use async/await now?

Is it safe to use async-await in Javascript instead of generators-promises now, knowing that the syntax has not made yet and will be coming with the release of ES8? What browsers can I count on it being available, and how common are the browsers…
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50
60
votes
1 answer

Is it possible to get stack traces across async/await boundaries using --harmony_async_await in Node 7?

We're experimenting with using --harmony_async_await in Node 7, and compared to transpiling with babel for async/await are missing the ability to have long stack traces (http://bluebirdjs.com/docs/api/promise.longstacktraces.html). Obviously, it…
james.haggerty
  • 1,170
  • 6
  • 10
60
votes
8 answers

ASP.NET Controller: An asynchronous module or handler completed while an asynchronous operation was still pending

I have a very simple ASP.NET MVC 4 controller: public class HomeController : Controller { private const string MY_URL = "http://smthing"; private readonly Task task; public HomeController() { task = DownloadAsync(); } …
dyatchenko
  • 2,283
  • 3
  • 22
  • 32
60
votes
1 answer

Stack traces with async/await

It's clear why stack traces are affected with Microsoft's new programming paradigm. We now have a semantic stack and a couple of physical ones (my choice of words). What I get to see is an exception's StackTrace property (and in the debugger) is the…
John
  • 6,693
  • 3
  • 51
  • 90
59
votes
5 answers

Async/Await - is it *concurrent*?

I've been considering the new async stuff in C# 5, and one particular question came up. I understand that the await keyword is a neat compiler trick/syntactic sugar to implement continuation passing, where the remainder of the method is broken up…
Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220
59
votes
3 answers

How do I synchronously return a value calculated in an asynchronous Future?

I am trying to use hyper to grab the content of an HTML page and would like to synchronously return the output of a future. I realized I could have picked a better example since synchronous HTTP requests already exist, but I am more interested in…
Boris
  • 991
  • 1
  • 9
  • 15
59
votes
7 answers

How to Exponential Backoff retry on kotlin coroutines

I am using kotlin coroutines for network request using extension method to call class in retrofit like this public suspend fun Call.await(): T { return suspendCancellableCoroutine { continuation -> enqueue(object : Callback
shakil.k
  • 1,623
  • 5
  • 17
  • 27
59
votes
5 answers

Pass async Callback to Timer constructor

I have async callback, which is passed into Timer(from System.Threading) constructor : private async Task HandleTimerCallback(object state) { if (timer == null) return; if (asynTaskCallback != null) { await…
demo
  • 6,038
  • 19
  • 75
  • 149
59
votes
5 answers

Use Task.Run() in synchronous method to avoid deadlock waiting on async method?

UPDATE The purpose of this question is to get a simple answer about Task.Run() and deadlocking. I very much understand the theoretical reasoning for not mixing async and sync, and I take them to heart. I'm not above learning new things from…
MikeJansen
  • 3,336
  • 3
  • 26
  • 37
59
votes
4 answers

Parallel.ForEach and async-await

I had such method: public async Task GetResult() { MyResult result = new MyResult(); foreach(var method in Methods) { string json = await Process(method); result.Prop1 = PopulateProp1(json); …
Sergino
  • 10,128
  • 30
  • 98
  • 159