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
11
votes
4 answers

Is it OK to declare an async method as returning void to silence the CS4014 warning?

Visual Studio emits a warning for this code ('because this call is not awaited, execution of the current method continues before the call is completed'). static void Main(string[] args) { FireAndForget(); // <-- Warning CS4014 // Do…
ZunTzu
  • 7,244
  • 3
  • 31
  • 39
11
votes
3 answers

Generator-based coroutine versus native coroutine

I just read PEP0492 talking about the new approach on coroutines but the PEP failed to make me understand the difference between generator-based coroutines and native ones. Can someone tell me the difference (maybe with examples)? For what I…
Koldar
  • 1,317
  • 15
  • 35
11
votes
3 answers

Can ConfigureAwait(false) in a library lose the synchronization context for the calling application?

I've read the advice many times from people smarter than me, and it has few caveats: Always use ConfigureAwait(false) inside library code. So I'm fairly certain I know the the answer, but I want to be 100%. The scenario is I have a library that…
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
11
votes
1 answer

Is it possible to tell if an object is awaitable at runtime?

I recently learned that any object with a GetAwaiter method returning an awaiter can be await-ed. This is true even if it's an extension method, meaning basically any object can be made await-able, if you so choose. But is there a way to tell at…
BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
11
votes
3 answers

Where to use concurrency when calling an API

Inside a c# project I'm making some calls to a web api, the thing is that I'm doing them within a loop in a method. Usually there are not so many but even though I was thinking of taking advantage of parallelism. What I am trying so far is public…
mitomed
  • 2,006
  • 2
  • 29
  • 58
11
votes
2 answers

SaveChangesAsync not updating value in database table

This is my Table:Statistics Id,Depth,RefreshCounter Sample Records: Id Depth RefreshCounter 1 1 1 2 1 0 3 1 0 4 1 0 Now what i need to do is whenever i am refreshing the page i…
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216
11
votes
3 answers

MongoDB (server v 2.6.7) with C# driver 2.0: How to get the result from InsertOneAsync

I am testing MongoDB (server v 2.6.7) with the C# driver 2.0. When I am using the insert function InsertOneAsync for a document with an _id which exists I am expecting an error like the one you get from the Mongo shell: WriteResult({ …
Fredrik
  • 127
  • 1
  • 1
  • 10
11
votes
3 answers

Create an Awaitable Cold Task

I have an async method after the completion of which I wish to run another method. This works fine if I simply call the method and add .ContinueWith() However, I have a new requirement which is to only start the task if I am able to add it to a…
Ewan
  • 1,261
  • 1
  • 14
  • 25
11
votes
2 answers

HttpClient - Send a batch of requests

I want to iterate a batch of requests, sending each one of them to an external API using HttpClient class. foreach (var MyRequest in RequestsBatch) { try { HttpClient httpClient = new HttpClient(); …
Alberto Montellano
  • 5,886
  • 7
  • 37
  • 53
11
votes
3 answers

Using IEnumerable.Aggregate with asynchronous calls

I'm trying to use the LINQ IEnumerable.Aggregate function to create a string consisting of files retrieved through async calls. Not a hundred percent sure that it's possible, and I'm also aware that there are other solutions, but I'd like to give it…
Don Simon
  • 591
  • 5
  • 17
11
votes
1 answer

AJAX call to async Task successfully hit the method but returns failed

I have an MVC controller (not api controller) [HttpPost] method public async Task PostDocument() to which I'm making an ajax call from client. And that method is making another API call to an [HttpPost] method PostDocument(DocRepoViewModel…
Rahul Chakrabarty
  • 2,149
  • 7
  • 39
  • 70
11
votes
3 answers

How does running several tasks asynchronously on UI thread using async/await work?

I've read (and used) async/await quite a lot for some time now but I still have one question I can't get an answer to. Say I have this code. private async void workAsyncBtn_Click(object sender, EventArgs e) { var myTask =…
Andreas
  • 2,336
  • 2
  • 28
  • 45
11
votes
2 answers

Pattern for writing synchronous and asynchronous methods in libraries and keeping it DRY

I'm modifying a library to add async methods. From Should I expose synchronous wrappers for asynchronous methods? it states I shouldn't just write a wrapper around Task.Result when calling the synchronous method. But how do I not have to duplicate a…
CharlesNRice
  • 3,219
  • 1
  • 16
  • 25
11
votes
6 answers

Capturing Exceptions on async operations

I'm reading up more about async here: http://msdn.microsoft.com/en-us/library/hh873173(v=vs.110).aspx Going through this example: Task [] recommendations = …; while(recommendations.Count > 0) { Task recommendation = await…
amhed
  • 3,649
  • 2
  • 31
  • 56
11
votes
2 answers

How to cancel a TaskCompletionSource using a timeout

I have the function that I call asynchronously using the await keyword: public Task RequestStateForEntity(EntityKey entity, string propName) { var tcs = new TaskCompletionSource(); try { var…
Retrocoder
  • 4,483
  • 11
  • 46
  • 72