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
12
votes
3 answers

How do I await a response from an RX Subject without introducing a race condition?

I have a service that allows a caller to send commands and receive responses asynchronously. In a real application, these actions are fairly disconnected (some action will send a command, and the responses will be process independently). However, in…
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
12
votes
2 answers

Why awaiting cold Task does not throw

I was just experimenting to see what happens when a cold task (i.e. a Task which hasn't been started) is awaited. To my surprise the code just hung forever and "Finsihed" is never printed. I would expect that an exception is thrown. public async…
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
12
votes
2 answers

AspNetSynchronizationContext and await continuations in ASP.NET

I noticed an unexpected (and I'd say, a redundant) thread switch after await inside asynchronous ASP.NET Web API controller method. For example, below I'd expect to see the same ManagedThreadId at locations #2 and 3#, but most often I see a…
noseratio
  • 59,932
  • 34
  • 208
  • 486
12
votes
2 answers

Tests show "await" is significantly slower, even when object being awaited is already Complete

I wanted to test the overhead ascribed to a program by using await/async. To test this, I wrote the following test class: public class Entity : INotifyCompletion { private Action continuation; private int i; public void…
Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
12
votes
2 answers

Exception handling inside "async void" WPF command handlers

I'm reviewing some WPF code of my colleagues, which is a library of UserControl-based components with a lot of async void event and command handlers. These methods currently do not implement any error handling internally. The code in a…
noseratio
  • 59,932
  • 34
  • 208
  • 486
12
votes
4 answers

Equivalent of ContinueWith(delegate, CancellationToken) with await continuation

I have that situation: private Task LongRunningTask = /* Something */; private void DoSomethingMore(Task previousTask) { } public Task IndependentlyCancelableSuccessorTask(CancellationToken cancellationToken) { return…
Jean Hominal
  • 16,518
  • 5
  • 56
  • 90
12
votes
2 answers

Response.Redirect issue with Asp.net async

I'm new to asp.net 4.5 async and am running into the following with calling response.redirect within an async method. The issue is that the response just "hangs" Has anyone else experienced similar issues with attempting an redirect with async? …
newman
  • 123
  • 1
  • 1
  • 4
12
votes
1 answer

Regarding the usage of SemaphoreSlim with Async/Await

I am not an advanced developer. I'm just trying to get a hold on the task library and just googling. I've never used the class SemaphoreSlim so I would like to know what it does. Here I present code where SemaphoreSlim is used with async & await but…
Thomas
  • 33,544
  • 126
  • 357
  • 626
12
votes
2 answers

What thread runs the code after the `await` keyword?

Let me just post a simple example: private void MyMethod() { Task task = MyAsyncMethod(); task.Wait(); } private async Task MyAsyncMethod() { //Code before await await MyOtherAsyncMethod(); …
AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
12
votes
1 answer

HttpContext.Current null inside async task

I have a method that uses a repository (userRepo): public override Task CreateLocalUserAsync(IUser user, string password, CancellationToken cancellationToken) { var task = new Task(() => { …
orourkedd
  • 6,201
  • 5
  • 43
  • 66
12
votes
3 answers

Check if Action is async lambda

Since I can define an Action as Action a = async () => { }; Can I somehow determine (at run time) whether the action a is async or not?
David Božjak
  • 16,887
  • 18
  • 67
  • 98
12
votes
2 answers

Better way to show error messages in async methods

The fact that we can't use the await keyword in catch blocks makes it quite awkward to show error messages from async methods in WinRT, since the MessageDialog API is asynchronous. Ideally I would like be able to write this: private async Task…
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
12
votes
2 answers

How to create C# async powershell method?

So I want to create a way to run a powershell script asynchronously. The below code is what I have so far, but it doesn't seem to be async because it locks up the application and the output is incorrect. public static string RunScript(string…
Ryan Currah
  • 1,067
  • 6
  • 15
  • 30
12
votes
2 answers

How to implement Android callbacks in C# using async/await with Xamarin or Dot42?

How do you implement callbacks in C# using async/await with Xamarin for Android? And how does this compare to standard Java programming for Android?
gregko
  • 5,642
  • 9
  • 49
  • 76
12
votes
3 answers

XmlWriter async methods

I have found example of async using of XmlWriter within msdn documentation http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx async Task TestWriter(Stream stream) { XmlWriterSettings settings = new XmlWriterSettings(); …
Aleks Antonenko
  • 131
  • 1
  • 5