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
294
votes
14 answers

How to write an async method with out parameter?

I want to write an async method with an out parameter, like this: public async void Method1() { int op; int result = await GetDataTaskAsync(out op); } How do I do this in GetDataTaskAsync?
jesse
  • 2,951
  • 2
  • 13
  • 4
291
votes
6 answers

asyncio.gather vs asyncio.wait (vs asyncio.TaskGroup)

asyncio.gather and asyncio.wait seem to have similar uses: I have a bunch of async things that I want to execute/wait for (not necessarily waiting for one to finish before the next one starts). Since Python 3.11 there is yet another similar feature,…
Claude
  • 8,806
  • 4
  • 41
  • 56
290
votes
3 answers

Where do I mark a lambda expression async?

I've got this code: private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args) { CheckBox ckbx = null; if (sender is CheckBox) { ckbx = sender as CheckBox; } if (null == ckbx) { …
283
votes
10 answers

Parallel foreach with asynchronous lambda

I would like to handle a collection in parallel, but I'm having trouble implementing it and I'm therefore hoping for some help. The trouble arises if I want to call a method marked async in C#, within the lambda of the parallel loop. For…
clausndk
  • 3,129
  • 2
  • 18
  • 14
282
votes
10 answers

What does the suspend function mean in a Kotlin Coroutine?

I'm reading Kotlin Coroutine and know that it is based on suspend function. But what does suspend mean? Can Coroutine or function get suspended? From https://kotlinlang.org/docs/reference/coroutines.html Basically, coroutines are computations that…
onmyway133
  • 45,645
  • 31
  • 257
  • 263
281
votes
15 answers

Call asynchronous method in constructor?

Summary: I would like to call an asynchronous method in a constructor. Is this possible? Details: I have a method called getwritings() that parses JSON data. Everything works fine if I just call getwritings() in an async method and put await to left…
281
votes
13 answers

Calling async method synchronously

I have an async method: public async Task GenerateCodeAsync() { string code = await GenerateCodeService.GenerateCodeAsync(); return code; } I need to call this method from a synchronous method. How can I do this without having to…
Catalin
  • 11,503
  • 19
  • 74
  • 147
268
votes
3 answers

await vs Task.Wait - Deadlock?

I don't quite understand the difference between Task.Wait and await. I have something similar to the following functions in a ASP.NET WebAPI service: public class TestController : ApiController { public static async Task Foo() { …
ronag
  • 49,529
  • 25
  • 126
  • 221
249
votes
7 answers

What is the use for Task.FromResult in C#

In C# and TPL (Task Parallel Library), the Task class represents an ongoing work that produces a value of type T. I'd like to know what is the need for the Task.FromResult method ? That is: In a scenario where you already have the produced value at…
lysergic-acid
  • 19,570
  • 21
  • 109
  • 218
244
votes
8 answers

When should I use Async Controllers in ASP.NET MVC?

I have some concerns using async actions in ASP.NET MVC. When does it improve performance of my apps, and when does it not? Is it good to use async action everywhere in ASP.NET MVC? Regarding awaitable methods: shall I use async/await keywords when…
Vnuuk
  • 6,177
  • 12
  • 40
  • 53
232
votes
8 answers

Create a completed Task

I want to create a completed Task (not Task). Is there something built into .NET to do this? A related question: Create a completed Task
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
229
votes
5 answers

How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?

Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often: (node:11057) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1):…
user1658162
  • 2,721
  • 2
  • 19
  • 23
229
votes
7 answers

Wait for an async void method

How can I wait for an async void method to finish its job? For example, I have a function like below: async void LoadBlahBlah() { await blah(); //... } Now I want to make sure that everything has been loaded before continuing somewhere…
MBZ
  • 26,084
  • 47
  • 114
  • 191
227
votes
10 answers

try/catch blocks with async/await

I'm digging into the node 7 async/await feature and keep stumbling across code like this function getQuote() { let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit laborum."; return quote; } async function main() { try { …
Patrick
  • 7,903
  • 11
  • 52
  • 87
227
votes
11 answers

Nesting await in Parallel.ForEach

In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop. The problem is that the parallel loop exits before the WCF calls are all complete. How would you…
Darthg8r
  • 12,377
  • 15
  • 63
  • 100