Questions tagged [async-await]
This covers the asynchronous programming model supported by various programming languages, using the async and await keywords.
async-await
27,504
questions
3218
votes
34
answers
2.3m
views
Using async/await with a forEach loop
Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.
import fs from 'fs-promise'
async function ...
1414
votes
26
answers
1.2m
views
How and when to use ‘async’ and ‘await’
From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic?
I'...
1391
votes
16
answers
1.3m
views
How to call asynchronous method from synchronous method in C#?
I have a public async Task Foo() method that I want to call from a synchronous method. So far all I have seen from MSDN documentation is calling async methods via async methods, but my whole program ...
937
votes
11
answers
705k
views
Syntax for an async arrow function
I can mark a JavaScript function as "async" (i.e., returning a promise) with the async keyword. Like this:
async function foo() {
// Do something
}
What is the equivalent syntax for arrow ...
782
votes
27
answers
1.4m
views
How can I wait In Node.js (JavaScript)? l need to pause for a period of time
I'm developing a console script for personal needs. I need to be able to pause for an extended amount of time, but, from my research, Node.js has no way to stop as required. It’s getting hard to read ...
764
votes
23
answers
556k
views
How would I run an async Task<T> method synchronously?
I am learning about async/await, and ran into a situation where I need to call an async method synchronously. How can I do that?
Async method:
public async Task<Customers> GetCustomers()
{
...
728
votes
19
answers
911k
views
Combination of async function + await + setTimeout
I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working:
async function asyncGenerator() {
// other code
...
680
votes
4
answers
285k
views
Best practice to call ConfigureAwait for all server-side code
When you have server-side code (i.e. some ApiController) and your functions are asynchronous - so they return Task<SomeObject> - is it considered best practice that any time you await functions ...
570
votes
10
answers
568k
views
Use async await with Array.map
Given the following code:
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item +...
563
votes
9
answers
270k
views
If my interface must return Task what is the best way to have a no-operation implementation?
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to ...
561
votes
8
answers
274k
views
Is Task.Result the same as .GetAwaiter.GetResult()?
I was recently reading some code that uses a lot of async methods, but then sometimes needs to execute them synchronously. The code does:
Foo foo = GetFooAsync(...).GetAwaiter().GetResult();
Is this ...
537
votes
8
answers
424k
views
Using async/await for multiple tasks
I'm using an API client that is completely asynchrounous, that is, each operation either returns Task or Task<T>, e.g:
static async Task DoSomething(int siteId, int postId, IBlogClient client)
{...
525
votes
9
answers
200k
views
Why can't I use the 'await' operator within the body of a lock statement?
The await keyword in C# (.NET Async CTP) is not allowed from within a lock statement.
From MSDN:
An
await expression cannot be used in a synchronous function, in a query
expression, in the catch or ...
523
votes
4
answers
186k
views
WaitAll vs WhenAll
What is the difference between Task.WaitAll() and Task.WhenAll() from the Async CTP?
Can you provide some sample code to illustrate the different use cases?
523
votes
17
answers
423k
views
How can I use async/await at the top level?
I have been going over async/await and after going over several articles, I decided to test things myself. However, I can't seem to wrap my head around why this does not work:
async function main() { ...
506
votes
13
answers
427k
views
How to safely call an async method in C# without await
I have an async method which returns no data:
public async Task MyAsyncMethod()
{
// do some stuff async, don't return any data
}
I'm calling this from another method which returns some data:
...
475
votes
17
answers
351k
views
Can constructors be async?
I have a project where I'm trying to populate some data in a constructor:
public class ViewModel
{
public ObservableCollection<TData> Data { get; set; }
async public ViewModel()
{
...
456
votes
2
answers
181k
views
What is the difference between asynchronous programming and multithreading?
I thought that they were basically the same thing — writing programs that split tasks between processors (on machines that have 2+ processors). Then I'm reading this, which says:
Async methods are ...
439
votes
2
answers
443k
views
When correctly use Task.Run and when just async-await
I would like to ask you on your opinion about the correct architecture when to use Task.Run. I am experiencing laggy UI in our WPF .NET 4.5
application (with Caliburn Micro framework).
Basically I am ...
430
votes
22
answers
410k
views
How can I invoke asynchronous code within a constructor?
At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on.
customElements.define('e-...
414
votes
12
answers
216k
views
Awaiting multiple Tasks with different results
I have 3 tasks:
private async Task<Cat> FeedCat() {}
private async Task<House> SellHouse() {}
private async Task<Tesla> BuyCar() {}
They all need to run before my code can continue ...
410
votes
11
answers
460k
views
Running multiple async tasks and waiting for them all to complete
I need to run multiple async tasks in a console application, and wait for them all to complete before further processing.
There's many articles out there, but I seem to get more confused the more I ...
401
votes
6
answers
345k
views
Any difference between await Promise.all() and multiple await?
Is there any difference between:
const [result1, result2] = await Promise.all([task1(), task2()]);
and
const t1 = task1();
const t2 = task2();
const result1 = await t1;
const result2 = await t2;
...
394
votes
10
answers
76k
views
Why use async and return await, when you can return Task<T> directly?
Is there any scenario where writing method like this:
public async Task<SomeResult> DoSomethingAsync()
{
// Some synchronous code might or might not be here... //
return await ...
382
votes
7
answers
256k
views
HttpClient.GetAsync(...) never returns when using await/async
Edit: This question looks like it might be the same problem, but has no responses...
Edit: In test case 5 the task appears to be stuck in WaitingForActivation state.
I've encountered some odd ...
380
votes
5
answers
155k
views
Synchronously waiting for an async operation, and why does Wait() freeze the program here
Preface: I'm looking for an explanation, not just a solution. I already know the solution.
Despite having spent several days studying MSDN articles about the Task-based Asynchronous Pattern (TAP), ...
379
votes
3
answers
450k
views
Do you have to put Task.Run in a method to make it async?
I'm trying to understand async await in the simplest form. I want to create a very simple method that adds two numbers for the sake of this example, granted, it's no processing time at all, it's just ...
375
votes
11
answers
108k
views
If async-await doesn't create any additional threads, then how does it make applications responsive?
Time and time again, I see it said that using async-await doesn't create any additional threads. That doesn't make sense because the only ways that a computer can appear to be doing more than 1 thing ...
369
votes
8
answers
125k
views
When would I use Task.Yield()?
I'm using async/await and Task a lot but have never been using Task.Yield() and to be honest even with all the explanations I do not understand why I would need this method.
Can somebody give a good ...
366
votes
15
answers
235k
views
How to call an async method from a getter or setter?
What'd be the most elegant way to call an async method from a getter or setter in C#?
Here's some pseudo-code to help explain myself.
async Task<IEnumerable> MyAsyncMethod()
{
return await ...
362
votes
6
answers
322k
views
Catch an exception thrown by an async void method
Using the async CTP from Microsoft for .NET,
is it possible to catch an exception thrown by an async method in the calling method?
public async void Foo()
{
var x = await DoSomethingAsync();
...
317
votes
5
answers
334k
views
asyncio.gather vs asyncio.wait (vs asyncio.TaskGroup)
asyncio.gather and asyncio.wait seem to have similar uses: I have a bunch of async things that I want to execute/wait for (not necessarily waiting for one to finish before the next one starts).
Since ...
311
votes
15
answers
222k
views
How to write an async method with out parameter?
I want to write an async method with an out parameter, like this:
public async void Method1()
{
int op;
int result = await GetDataTaskAsync(out op);
}
How do I do this in GetDataTaskAsync?
309
votes
10
answers
243k
views
What does the suspend function mean in a Kotlin Coroutine?
I'm reading Kotlin Coroutine and know that it is based on suspend function. But what does suspend mean?
Can Coroutine or function get suspended?
From https://kotlinlang.org/docs/reference/coroutines....
303
votes
3
answers
252k
views
Where do I mark a lambda expression async?
I've got this code:
private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args)
{
CheckBox ckbx = null;
if (sender is CheckBox)
{
ckbx = ...
301
votes
11
answers
278k
views
Parallel foreach with asynchronous lambda
I would like to handle a collection in parallel, but I'm having trouble implementing it and I'm therefore hoping for some help.
The trouble arises if I want to call a method marked async in C#, ...
292
votes
15
answers
270k
views
Call asynchronous method in constructor?
Summary: I would like to call an asynchronous method in a constructor. Is this possible?
Details: I have a method called getwritings() that parses JSON data. Everything works fine if I just call ...
286
votes
13
answers
338k
views
Calling async method synchronously
I have an async method:
public async Task<string> GenerateCodeAsync()
{
string code = await GenerateCodeService.GenerateCodeAsync();
return code;
}
I need to call this method ...
278
votes
3
answers
273k
views
await vs Task.Wait - Deadlock? [duplicate]
I don't quite understand the difference between Task.Wait and await.
I have something similar to the following functions in a ASP.NET WebAPI service:
public class TestController : ApiController
{
...
261
votes
7
answers
151k
views
What is the use for Task.FromResult<TResult> in C#
In C# and TPL (Task Parallel Library), the Task class represents an ongoing work that produces a value of type T.
I'd like to know what is the need for the Task.FromResult method ?
That is: In a ...
260
votes
10
answers
312k
views
Simplest async/await example possible in Python
I've read many examples, blog posts, questions/answers about asyncio / async / await in Python 3.5+, many were complex, the simplest I found was probably this one.
Still it uses ensure_future, and for ...
246
votes
8
answers
141k
views
When should I use Async Controllers in ASP.NET MVC?
I have some concerns using async actions in ASP.NET MVC. When does it improve performance of my apps, and when does it not?
Is it good to use async action everywhere in ASP.NET MVC?
Regarding ...
241
votes
8
answers
226k
views
Wait for an async void method
How can I wait for an async void method to finish its job?
For example, I have a function like below:
async void LoadBlahBlah()
{
await blah();
//...
}
Now I want to make sure that everything ...
238
votes
7
answers
94k
views
Difference between `return await promise` and `return promise`
Given the code samples below, is there any difference in behavior, and, if so, what are those differences?
return await promise
async function delay1Second() {
return (await delay(1000));
}
...
236
votes
8
answers
134k
views
Create a completed Task
I want to create a completed Task (not Task<T>). Is there something built into .NET to do this?
A related question:
Create a completed Task<T>
234
votes
10
answers
413k
views
try/catch blocks with async/await
I'm digging into the node 7 async/await feature and keep stumbling across code like this
function getQuote() {
let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit laborum.";
...
233
votes
5
answers
95k
views
How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?
Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often:
(node:11057) UnhandledPromiseRejectionWarning: Unhandled ...
232
votes
12
answers
296k
views
Using filesystem in node.js with async / await
I would like to use async/await with some filesystem operations. Normally async/await works fine because I use babel-plugin-syntax-async-functions.
But with this code I run into the if case where ...
229
votes
11
answers
175k
views
Nesting await in Parallel.ForEach [duplicate]
In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop. The problem is that the parallel loop exits ...
226
votes
3
answers
215k
views
How do you create an asynchronous method in C#?
Every blog post I've read tells you how to consume an asynchronous method in C#, but for some odd reason never explain how to build your own asynchronous methods to consume. So I have this code right ...