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
83
votes
5 answers

Async always WaitingForActivation

I am trying to figure out what the async & await keywords are all about, however the output isn't what I'm expecting. The console application is as follows: class Program { static void Main(string[] args) { Console.WriteLine("Foo…
BanksySan
  • 27,362
  • 33
  • 117
  • 216
83
votes
5 answers

Understanding async / await in C#

I'm starting to learn about async / await in C# 5.0, and I don't understand it at all. I don't understand how it can be used for parallelism. I've tried the following very basic program: using System; using System.Collections.Generic; using…
Alex Marshall
  • 10,162
  • 15
  • 72
  • 117
83
votes
5 answers

How to Async Files.ReadAllLines and await for results?

I have the following code, private void button1_Click(object sender, RoutedEventArgs e) { button1.IsEnabled = false; var s = File.ReadAllLines("Words.txt").ToList(); // my WPF app hangs here // do something with s …
user677607
82
votes
3 answers

Is it possible to get a good stack trace with .NET async methods?

I have the following sample code setup in a WebApi application: [HttpGet] public double GetValueAction() { return this.GetValue().Result; } public async Task GetValue() { return await…
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152
82
votes
4 answers

What's the difference between InvokeAsync and BeginInvoke for WPF Dispatcher

I noticed in .NET 4.5 that the WPF Dispatcher had gotten a new set of methods to execute stuff on the Dispatcher's thread called InvokeAsync. Before, .NET 4.5 we had Invoke and BeginInvoke which handled this syncronously and asynchronously…
Isak Savo
  • 34,957
  • 11
  • 60
  • 92
82
votes
5 answers

How do I test an async method with NUnit (or possibly with another framework)?

I have an ASP.NET Web API application, with an ApiController that features asynchronous methods, returning Task<> objects and marked with the async keyword. public class MyApiController : ApiController { public async Task
aknuds1
  • 65,625
  • 67
  • 195
  • 317
81
votes
15 answers

Verify that an exception is thrown using Mocha / Chai and async/await

I'm struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await. Here's an example that works, but I dislike that should.be.rejectedWith returns a promise that needs to be returned from the test…
plexer
  • 4,542
  • 2
  • 23
  • 27
81
votes
10 answers

Is there a way to short circuit async/await flow?

All four functions are called below in update return promises. async function update() { var urls = await getCdnUrls(); var metadata = await fetchMetaData(urls); var content = await fetchContent(metadata); await render(content); …
sbr
  • 4,735
  • 5
  • 43
  • 49
81
votes
1 answer

await Task.Delay() vs. Task.Delay().Wait()

In C# I have the following two simple examples: [Test] public void TestWait() { var t = Task.Factory.StartNew(() => { Console.WriteLine("Start"); Task.Delay(5000).Wait(); Console.WriteLine("Done"); }); …
svenskmand
  • 813
  • 1
  • 6
  • 5
80
votes
3 answers

Getting return value from Task.Run

I have the following code: public static async Task Start(IProgress progress) { const int total = 10; for (var i = 0; i <= total; i++) { await Task.Run(() =>…
Null Reference
  • 11,260
  • 40
  • 107
  • 184
79
votes
5 answers

multiple awaits vs Task.WaitAll - equivalent?

In terms of performance, will these 2 methods run GetAllWidgets() and GetAllFoos() in parallel? Is there any reason to use one over the other? There seems to be a lot happening behind the scenes with the compiler so I don't find it…
vidalsasoon
  • 4,365
  • 1
  • 32
  • 40
79
votes
1 answer

.Net Invoke async method and await

I have an ansyc method public Task GetCar() { } I can call this method async and await: Car car = await GetCar() How can I invoke the method using MethodInfo.Invoke and await for the result asynchronously. MethodInfo method =…
ajp
  • 1,440
  • 2
  • 13
  • 25
79
votes
1 answer

Await operator can only be used within an Async method

I'm trying to make a simple program to test the new .NET async functionality within Visual Studio 2012. I generally use BackgroundWorkers to run time-consuming code asynchronously, but sometimes it seems like a hassle for a relatively simple (but…
William Thomas
  • 2,108
  • 3
  • 22
  • 32
78
votes
3 answers

Is `async/await` available in Vue.js `mounted`?

I'd like to do something like this in mounted() {}: await fetchData1(); await fetchData2UsingData1(); doSomethingUsingData1And2(); So I wonder if this works: async mounted() { await fetchData1(); await fetchData2UsingData1(); …
Taichi
  • 2,297
  • 6
  • 25
  • 47
77
votes
9 answers

using async await and .then together

Is there any harm in using async/await and .then().catch() together such as: async apiCall(params) { var results = await this.anotherCall() .then(results => { //do any results transformations return results; }) …
PixelPaul
  • 1,022
  • 1
  • 10
  • 18