An async/await example that causes a deadlock

Take a look at this example, Stephen has a clear answer for you: So this is what happens, starting with the top-level method (Button1_Click for UI / MyController.Get for ASP.NET): The top-level method calls GetJsonAsync (within the UI/ASP.NET context). GetJsonAsync starts the REST request by calling HttpClient.GetStringAsync (still within the context). GetStringAsync returns an uncompleted … Read more

Is it an anti-pattern to use async/await inside of a new Promise() constructor?

You’re effectively using promises inside the promise constructor executor function, so this the Promise constructor anti-pattern. Your code is a good example of the main risk: not propagating all errors safely. Read why there. In addition, the use of async/await can make the same traps even more surprising. Compare: let p = new Promise(resolve => … Read more

How and when to use ‘async’ and ‘await’

When using async and await the compiler generates a state machine in the background. Here’s an example on which I hope I can explain some of the high-level details that are going on: public async Task MyMethodAsync() { Task<int> longRunningTask = LongRunningOperationAsync(); // independent work which doesn’t need the result of LongRunningOperationAsync can be done … Read more

How to make a method async with async and await?

The reason for async-await is, that whenever your thread has to wait for some other process to finish, your thread can look around to see if it can do something useful instead of waiting idly. This is especially useful for communication oriented tasks: query data from a database, fetching information from the internet, writing data … Read more

How to call an async method from another method

The best practice for async/await is to use async “all the way down” (unless you really and truly don’t care about Method1 waiting for Method2 to complete). It’s possible to mix Task.Wait (or similar constructs) with async code, but it’s a bad idea because it can lead to deadlocks. The best thing here would be, … Read more