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
468
votes
15 answers

How can I use async/await at the top level?

I have been going over async/await and after going over several articles, I decided to test things myself. However, I can't seem to wrap my head around why this does not work: async function main() { var value = await Promise.resolve('Hey…
Felipe
  • 10,606
  • 5
  • 40
  • 57
463
votes
16 answers

Can constructors be async?

I have a project where I'm trying to populate some data in a constructor: public class ViewModel { public ObservableCollection Data { get; set; } async public ViewModel() { Data = await GetDataTask(); } public…
Marty Neal
  • 8,741
  • 3
  • 33
  • 38
439
votes
2 answers

What is the difference between asynchronous programming and multithreading?

I thought that they were basically the same thing — writing programs that split tasks between processors (on machines that have 2+ processors). Then I'm reading this, which says: Async methods are intended to be non-blocking operations. An…
426
votes
2 answers

When correctly use Task.Run and when just async-await

I would like to ask you on your opinion about the correct architecture when to use Task.Run. I am experiencing laggy UI in our WPF .NET 4.5 application (with Caliburn Micro framework). Basically I am doing (very simplified code snippets): public…
Lukas K
  • 6,037
  • 4
  • 23
  • 31
397
votes
21 answers

Async/Await Class Constructor

At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on. customElements.define('e-mail', class extends HTMLElement { async…
Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
387
votes
12 answers

Awaiting multiple Tasks with different results

I have 3 tasks: private async Task FeedCat() {} private async Task SellHouse() {} private async Task BuyCar() {} They all need to run before my code can continue and I need the results from each as well. None of the results have…
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
384
votes
11 answers

Running multiple async tasks and waiting for them all to complete

I need to run multiple async tasks in a console application, and wait for them all to complete before further processing. There's many articles out there, but I seem to get more confused the more I read. I've read and understand the basic principles…
Daniel Minnaar
  • 5,865
  • 5
  • 31
  • 52
376
votes
5 answers

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Preface: I'm looking for an explanation, not just a solution. I already know the solution. Despite having spent several days studying MSDN articles about the Task-based Asynchronous Pattern (TAP), async and await, I'm still a bit confused about some…
373
votes
3 answers

Do you have to put Task.Run in a method to make it async?

I'm trying to understand async await in the simplest form. I want to create a very simple method that adds two numbers for the sake of this example, granted, it's no processing time at all, it's just a matter of formulating an example here. Example…
Neal
  • 9,487
  • 15
  • 58
  • 101
371
votes
7 answers

HttpClient.GetAsync(...) never returns when using await/async

Edit: This question looks like it might be the same problem, but has no responses... Edit: In test case 5 the task appears to be stuck in WaitingForActivation state. I've encountered some odd behaviour using the System.Net.Http.HttpClient in .NET…
Benjamin Fox
  • 5,624
  • 5
  • 19
  • 19
368
votes
6 answers

Any difference between await Promise.all() and multiple await?

Is there any difference between: const [result1, result2] = await Promise.all([task1(), task2()]); and const t1 = task1(); const t2 = task2(); const result1 = await t1; const result2 = await t2; and const [t1, t2] = [task1(), task2()]; const…
Hidden
  • 3,895
  • 3
  • 11
  • 11
366
votes
11 answers

If async-await doesn't create any additional threads, then how does it make applications responsive?

Time and time again, I see it said that using async-await doesn't create any additional threads. That doesn't make sense because the only ways that a computer can appear to be doing more than 1 thing at a time is Actually doing more than 1 thing at…
Ms. Corlib
  • 4,993
  • 4
  • 12
  • 19
365
votes
9 answers

Why use async and return await, when you can return Task directly?

Is there any scenario where writing method like this: public async Task DoSomethingAsync() { // Some synchronous code might or might not be here... // return await DoAnotherThingAsync(); } instead of this: public…
TX_
  • 5,056
  • 3
  • 28
  • 40
354
votes
6 answers

Catch an exception thrown by an async void method

Using the async CTP from Microsoft for .NET, is it possible to catch an exception thrown by an async method in the calling method? public async void Foo() { var x = await DoSomethingAsync(); /* Handle the result, but sometimes an exception…
TimothyP
  • 21,178
  • 26
  • 94
  • 142
345
votes
5 answers

When would I use Task.Yield()?

I'm using async/await and Task a lot but have never been using Task.Yield() and to be honest even with all the explanations I do not understand why I would need this method. Can somebody give a good example where Yield() is required?
Krumelur
  • 32,180
  • 27
  • 124
  • 263