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
124
votes
9 answers

How can I call an async method in Main?

public class test { public async Task Go() { await PrintAnswerToLife(); Console.WriteLine("done"); } public async Task PrintAnswerToLife() { int answer = await GetAnswerToLife(); …
Larry
  • 2,172
  • 2
  • 14
  • 20
123
votes
8 answers

In JavaScript, does using await inside a loop block the loop?

Take the following loop: for(var i=0; i<100; ++i){ let result = await some_slow_async_function(); do_something_with_result(); } Does await block the loop? Or does the i continue to be incremented while awaiting? Is the order of…
smerg
  • 1,506
  • 3
  • 10
  • 14
121
votes
2 answers

Async/Await vs Threads

In .Net 4.5 Microsoft has added the new Async/Await feature to simplify asynchronous coding. However, I wonder Can Async/Await completely replace the old way of using Threads? Is Async/Await capable of doing whatever a Thread can…
Roman Ratskey
  • 5,101
  • 8
  • 44
  • 67
120
votes
3 answers

What is the advantage of using async with MVC5?

What is the difference between: public ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { IdentityResult result = IdentityManager.Authentication.CheckPasswordAndSignIn(AuthenticationManager,…
116
votes
3 answers

Async call with await in HttpClient never returns

I have a call I am making from inside a xaml-based, C# metro application on the Win8 CP; this call simply hits a web service and returns JSON data. HttpMessageHandler handler = new HttpClientHandler(); HttpClient httpClient = new…
keithwarren7
  • 14,094
  • 8
  • 53
  • 74
116
votes
8 answers

Async / await vs then which is the best for performance?

I have a simple code in JavaScript that execute a request in an API and return the response, simple. But in this case I will have thousands of requests. So, which one of the code options will perform better, and why. Also which one is recommended as…
Francisco
  • 1,307
  • 2
  • 8
  • 7
116
votes
5 answers

Why does this async action hang when I try and access the Result property of my Task?

I have a multi-tier .Net 4.5 application calling a method using C#'s new async and await keywords that just hangs and I can't see why. At the bottom I have an async method that extents our database utility OurDBConn (basically a wrapper for the…
Keith
  • 150,284
  • 78
  • 298
  • 434
115
votes
2 answers

Await vs Task.Result in an Async Method

What's the difference between doing the following: async Task method(){ var r = await dynamodb.GetItemAsync(...) return r.Item; } vs async Task method(){ var task = dynamodb.GetItemAsync(...) return task.Result.Item; } In my…
luis
  • 2,067
  • 2
  • 13
  • 21
115
votes
3 answers

Entity Framework SaveChanges() vs. SaveChangesAsync() and Find() vs. FindAsync()

I have been searching for the differences between 2 pairs above but haven't found any articles explaining clearly about it as well as when to use one or another. So what is the difference between SaveChanges() and SaveChangesAsync()? And between…
Hien Tran
  • 1,443
  • 2
  • 12
  • 19
115
votes
2 answers

How to use RestSharp with async/await

I'm struggling to find a modern example of some asynchronous C# code that uses RestSharp with async and await. I know there's been a recent update by Haack but I don't know how to use the new methods. Also, how can I provide a cancellation token so…
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
114
votes
6 answers

Will async/await block a thread node.js

When async/await used in a node.js function, will it block the node.js thread untill it executes the next line of code ?
Rajesh
  • 1,514
  • 2
  • 14
  • 15
112
votes
2 answers

Why should I create async WebAPI operations instead of sync ones?

I have the following operation in a Web API I created: // GET api/ [HttpGet] [Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")] public CartTotalsDTO GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri]…
David Jiménez Martínez
  • 3,053
  • 5
  • 23
  • 43
111
votes
6 answers

How to use await in a loop

I'm trying to create an asynchronous console app that does a some work on a collection. I have one version which uses parallel for loop another version that uses async/await. I expected the async/await version to work similar to parallel version but…
Satish
  • 3,020
  • 7
  • 35
  • 47
110
votes
5 answers

Using "await" inside non-async function

I have an async function that runs by a setInterval somewhere in my code. This function updates some cache in regular intervals. I also have a different, synchronous function which needs to retrieve values - preferably from the cache, yet if it's a…
crogs
  • 1,103
  • 2
  • 7
  • 4
110
votes
4 answers

Any difference between "await Task.Run(); return;" and "return Task.Run()"?

Is there any conceptual difference between the following two pieces of code: async Task TestAsync() { await Task.Run(() => DoSomeWork()); } and Task TestAsync() { return Task.Run(() => DoSomeWork()); } Does the generated code differ,…
avo
  • 10,101
  • 13
  • 53
  • 81