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
109
votes
2 answers

HttpClient.GetAsync with network credentials

I'm currently using HttpWebRequest to get a website. I'd like to use the await pattern, which is not given for HttpWebRequests. I found the class HttpClient, which seems to be the new Http worker class. I'm using HttpClient.GetAsync(...) to query my…
Jan K.
  • 2,542
  • 2
  • 21
  • 30
108
votes
5 answers

How do yield and await implement flow of control in .NET?

As I understand the yield keyword, if used from inside an iterator block, it returns flow of control to the calling code, and when the iterator is called again, it picks up where it left off. Also, await not only waits for the callee, but it returns…
John Wu
  • 50,556
  • 8
  • 44
  • 80
105
votes
7 answers

Why is HttpContext.Current null after await?

I have the following test WebAPI code, I don't use WebAPI in production but I made this because of a discussion I had on this question: WebAPI Async question Anyways, here's the offending WebAPI method: public async Task Get(int id) { …
welegan
  • 3,013
  • 3
  • 15
  • 20
105
votes
5 answers

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task'

I am new to asynchronous programming, so after going through some async sample codes, I thought of writing a simple async code I created a simple Winform application and inside the Form I wrote the following code. But its just not working private…
techBeginner
  • 3,792
  • 11
  • 43
  • 59
104
votes
4 answers

What's the "right way" to use HttpClient synchronously?

I used quote marks around "right way" because I'm already well aware that the right way to use an asynchronous API is to simply let the asynchronous behavior propagate throughout the entire call chain. That's not an option here. I'm dealing with a…
spoonraker
  • 1,277
  • 2
  • 11
  • 12
104
votes
1 answer

Horrible performance using SqlCommand Async methods with large data

I'm having major SQL performance problems when using async calls. I have created a small case to demonstrate the problem. I have create a database on a SQL Server 2016 which resides in our LAN (so not a localDB). In that database, I have a table…
hcd
  • 1,338
  • 2
  • 10
  • 15
101
votes
6 answers

Promise equivalent in C#

In Scala there is a Promise class that could be used to complete a Future manually. I am looking for an alternative in C#. I am writing a test and I want it to look it similar to this: // var MyResult has a field `Header` var promise = new…
eddyP23
  • 6,420
  • 7
  • 49
  • 87
100
votes
1 answer

What does asyncio.create_task() do?

What does asyncio.create_task() do? I have looked at the docs and can't seem to understand it. A bit of code that confuses me is this: import asyncio async def counter_loop(x, n): for i in range(1, n + 1): print(f"Counter {x}: {i}") …
BeastCoder
  • 2,391
  • 3
  • 15
  • 26
100
votes
5 answers

Combine awaitables like Promise.all

In asynchronous JavaScript, it is easy to run tasks in parallel and wait for all of them to complete using Promise.all: async function bar(i) { console.log('started', i); await delay(1000); console.log('finished', i); } async function foo()…
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
99
votes
9 answers

How to fix "'throw' of exception caught locally"?

In this function that handles a REST API call, any of the called functions to handle parts of the request might throw an error to signal that an error code should be sent as response. However, the function itself might also discover an error, at…
cib
  • 2,124
  • 2
  • 21
  • 23
98
votes
5 answers

Correct async function export in node.js

I had my custom module with following code: module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) { ... } It worked fine if call the function outside my module, however if I called inside I got error while…
Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101
98
votes
6 answers

Does the use of async/await create a new thread?

I am new to TPL and I am wondering: How does the asynchronous programming support that is new to C# 5.0 (via the new async and await keywords) relate to the creation of threads? Specifically, does the use of async/await create a new thread each time…
dev hedgehog
  • 8,698
  • 3
  • 28
  • 55
96
votes
4 answers

A good solution for await in try/catch/finally?

I need to call an async method in a catch block before throwing again the exception (with its stack trace) like this : try { // Do something } catch { // <- Clean things here with async methods throw; } But unfortunately you can't use…
user2397050
  • 963
  • 1
  • 7
  • 4
95
votes
5 answers

Testing for exceptions in async methods

I'm a bit stuck with this code (this is a sample): public async Task Fail() { await Task.Run(() => { throw new Exception(); }); } [Test] public async Task TestFail() { Action a = async () => { await Fail(); }; …
Eugene
  • 1,073
  • 1
  • 7
  • 7
95
votes
6 answers

How to await a list of tasks asynchronously using LINQ?

I have a list of tasks that I created like this: public async Task> GetFoosAndDoSomethingAsync() { var foos = await GetFoosAsync(); var tasks = foos.Select(async foo => await DoSomethingAsync(foo)).ToList(); ... } By using…
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575