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

Could awaiting network cause client timeouts?

I have a server that is doing work instructed by an Azure queue. It is almost always on very high CPU doing multiple tasks in parallel and some of the tasks use Parallel.ForEach. During the running of the tasks I write analytic events to another…
Moti Azu
  • 5,392
  • 1
  • 23
  • 32
11
votes
1 answer

Using async await inside the timer_elapsed event handler within a windows service

I have a timer in a Windows Service, and there is a call made to an async method inside the timer_Elapsed event handler: protected override void OnStart(string[] args) { timer.Start(); } private async void timer_Elapsed(object sender,…
Prabhu
  • 12,995
  • 33
  • 127
  • 210
11
votes
2 answers

Using a generic type as a return type of an async method

A previous question made me wonder why the following method would raise a compile time error: The return type of an async method must be void, Task or Task public async T MyMethodAsync() where T : Task { // Irrelevant code here which…
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
11
votes
1 answer

Why are Awaiters (async/await) structs and not classes? Can classes be used?

Why are the awaiters (GetAwaiter - to make a class awaitable) structs and not classes. Does it harm to use a class? public struct ConfiguredTaskAwaiter :…
Thomas Maierhofer
  • 2,665
  • 18
  • 33
11
votes
2 answers

Limit parallelism of an Async method and not block a Thread-Pool thread

I have an asynchronous method RequestInternalAsync() which makes requests to an external resource, and want to write a wrapper method which limits a number of concurrent asynchronous requests to the method by reducing parallelism. First option, that…
Sergey Kostrukov
  • 1,143
  • 15
  • 24
11
votes
2 answers

Log4net LogicalThreadContext not working as expected

I've been trying to use Log4nets LogicalThreadContext to provide context to each of my log entries. My application uses async/await quite heavily, but from reading various articles the LogicalThreadContext should work properly with asynchronous…
Richard
  • 1,602
  • 1
  • 15
  • 16
11
votes
7 answers

What's C#'s await equivalent in javascript/jquery?

I'm using a jQuery library called bootbox bootbox.dialog({ title: "Group", buttons: { success: { label: "OK", className: "btn-success", callback: function () { postForm(); …
Null Reference
  • 11,260
  • 40
  • 107
  • 184
11
votes
3 answers

ConfigureAwait pushes the continuation to a pool thread

Here is some WinForms code: async void Form1_Load(object sender, EventArgs e) { // on the UI thread Debug.WriteLine(new { where = "before", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread }); var…
noseratio
  • 59,932
  • 34
  • 208
  • 486
11
votes
2 answers

How do I force a Task to stop?

I am using a Task with a CancellationTokenSource provided, and within my task I always check if cancellation is requested and stop executing if requested - in the parts of the code that I control. The problem is that within this task, I use very…
ldam
  • 4,412
  • 6
  • 45
  • 76
11
votes
1 answer

Why does a bool "flag" get generated for the async/await state machine?

If you compile the following code: private async Task M() { return await Task.FromResult(0); } And then decompile it (I used dotPeek) and examine the all-important MoveNext method, you will see a bool variable declared near the beginning;…
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
11
votes
2 answers

How Microsoft.Bcl.Async works?

Microsoft.Bcl.Async enables developers to use async/await keywords without .NET Framework 4.5 that they are supposed to target to use them. That's great, thanks to the incredibly hard work of people in the Microsoft CLR and language teams. Now I am…
Dean Seo
  • 5,486
  • 3
  • 30
  • 49
11
votes
2 answers

How do I convert this to an async task?

Given the following code... static void DoSomething(int id) { Thread.Sleep(50); Console.WriteLine(@"DidSomething({0})", id); } I know I can convert this to an async task as follows... static async Task DoSomethingAsync(int id) { await…
Martin Robins
  • 6,033
  • 10
  • 58
  • 95
11
votes
1 answer

Task Cancelled Exception (ThrowForNonSuccess)

This is a continuation from this question: Multiple Task Continuation I have changed my code as in the answer, however now I am receiving TaskCancelledExceptions when I try to run tasks. public virtual async Task RunAsync(TaskWithProgress task) { …
Simon
  • 9,197
  • 13
  • 72
  • 115
11
votes
3 answers

How to copy HttpContent async and cancelable?

I'm using HttpClient.PostAsync() and the response is an HttpResponseMessage. Its Content property is of type HttpContent which has a CopyToAsync() method. Unfortunately, this is not cancelable. Is there a way to get the response copied into a Stream…
Krumelur
  • 32,180
  • 27
  • 124
  • 263
11
votes
2 answers

CPU underutilized. Due to blocking I/O?

I am trying to find where lies the bottleneck of a C# server application which underutilize CPU. I think this may be due to poor disk I/O performance and has nothing to do with the application itself but I am having trouble making a fact out of this…
darkey
  • 3,672
  • 3
  • 29
  • 50