Can anyone explain what the await
function does?

- 7,252
- 16
- 46
- 65

- 10,256
- 7
- 39
- 49
-
1Is this what you are referring to? [Asynchronous Programming in C# 5.0 part two: Whence await?](http://blogs.msdn.com/b/ericlippert/archive/2010/10/29/asynchronous-programming-in-c-5-0-part-two-whence-await.aspx) – jordanbtucker Oct 30 '10 at 05:23
-
1See also [Asynchronous Programming with Async and Await](http://msdn.microsoft.com/en-us/library/hh191443.aspx) – Robert Harvey Jan 16 '15 at 21:16
-
Nice examples also at http://www.dotnetperls.com/async. – Miljen Mikic Nov 12 '15 at 12:46
-
I don't believe this question is too broad or should be closed. It's asking what one keyword means. (Was an earlier version different somehow?) – Panzercrisis Aug 26 '16 at 13:03
5 Answers
They just talked about this at PDC yesterday!
Await is used in conjunction with Tasks (parallel programming) in .NET. It's a keyword being introduced in the next version of .NET. It more or less lets you "pause" the execution of a method to wait for the Task to complete execution. Here's a brief example:
//create and run a new task
Task<DataTable> dataTask = new Task<DataTable>(SomeCrazyDatabaseOperation);
//run some other code immediately after this task is started and running
ShowLoaderControl();
StartStoryboard();
//this will actually "pause" the code execution until the task completes. It doesn't lock the thread, but rather waits for the result, similar to an async callback
// please so also note, that the task needs to be started before it can be awaited. Otherwise it will never return
dataTask.Start();
DataTable table = await dataTask;
//Now we can perform operations on the Task result, as if we're executing code after the async operation completed
listBoxControl.DataContext = table;
StopStoryboard();
HideLoaderControl();

- 16,092
- 13
- 59
- 98

- 1,360
- 10
- 11
-
2When is it the C# form of promises: http://en.wikipedia.org/wiki/Futures_and_promises – Oct 30 '10 at 06:07
-
12
-
10
-
20For the sake of completness, let's add that the above piece of code must be wrapped in a method that is adorned with an async keyword. This method shall immediately return as soon as the first await keyword is encountered therein. – Przemek Nov 01 '10 at 07:53
-
Also worth mentioning that in a the body of code written AFTER the 'await' keyword is rewritten by the compiler to form the callback method. So a synchronous coding style with the benefits of asynchronous execution. – EightyOne Unite Nov 25 '10 at 14:38
-
14In your words: it lets you "pause" the method, but it should be noted that it doesn't pause or block the thread. – Matt Wonlaw Dec 07 '10 at 06:03
-
2@mlaw: I think too much is being made of that distinction. It *does* block the conceptual thread of excecution, and that *may* correspond to an OS thread - but the details depend on the scheduler. It really is a thread - just not the OS thread. That's not irrelevant, but in terms of understanding program flow (and these are control flow constructs) it's not important. – Eamon Nerbonne Jan 12 '11 at 15:54
-
What's the difference to using a WaitHandle and then call WaitAll() or WaitAny()? – Krumelur Mar 19 '11 at 20:40
-
2This answer is misleading. `await` does not pause anything, it wraps the rest or the method in continuation task if `Task` awaited is still running. – Anri Feb 15 '13 at 15:01
-
"It more or less lets you "pause" the execution of a method to wait for the Task to complete execution". WAIT. You want to say - await MyFunctionAsync() is THE SAME as just MyFunction() ? await kills async, MyFunction() remains. WTF do we need await async for ? – monstro Jan 16 '14 at 02:41
-
First they make Async functions, then, they make up "await" operator (or whatever it is) to make that Async function normal synchronous function :))) – monstro Jan 16 '14 at 02:44
-
This example does not demonstrate the power of await used with Task. It starts a Task, and immediately wait for it to finish. We should add something between Task.start() and await. – user926958 Mar 12 '14 at 00:50
Basically, the async
and await
keywords allow you to specify that execution of a method should stop at all usages of await
, which mark asynchronous method calls, and then resume once the asynchronous operation is complete. This allows you to call a method in an app's main thread and handle complex work asynchronously, without the need to explicitly define threads and joins or blocking the app's main thread.
Think of it as being somewhat similar to a yield return
statement in a method producing an IEnumerable. When the runtime hits the yield
, it will basically save the method's current state, and return the value or reference being yielded. The next time IEnumerator.MoveNext() is called on the return object (which is generated internally by the runtime), the method's old state is restored to the stack and execution continues with the next line after the yield return
as if we'd never left the method. Without this keyword, an IEnumerator type must be custom-defined to store state and handle the iteration requests, with methods that can become VERY complex indeed.
Similarly, a method marked as async
must have at least one await
. On an await
, the runtime will save the current thread's state and call stack, make the asynchronous call, and unwind back to the runtime's message loop to handle the next message and keep the app responsive. When the asynchronous operation is complete, at the next scheduling opportunity, the call stack to up the async operation is pushed back in and continued as if the call was synchronous.
So, these two new keywords basically simplify the coding of asynchronous processes, much like yield return
simplified the generation of custom enumerables. With a couple keywords and a little background knowledge, you can skip all the confusing and often error-prone details of a traditional asynchronous pattern. This will be INVALUABLE in pretty much any event-driven GUI app like Winforms, WPF of Silverlight.

- 70,210
- 21
- 112
- 164
The currently accepted answer is misleading.
await
is not pausing anything.
First of all it can be used only in methods or lambdas marked as async
and returning Task
or void
if you don't care having Task
instance running in this method.
Here is an illustration:
internal class Program
{
private static void Main(string[] args)
{
var task = DoWork();
Console.WriteLine("Task status: " + task.Status);
Console.WriteLine("Waiting for ENTER");
Console.ReadLine();
}
private static async Task DoWork()
{
Console.WriteLine("Entered DoWork(). Sleeping 3");
// imitating time consuming code
// in a real-world app this should be inside task,
// so method returns fast
Thread.Sleep(3000);
await Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("async task iteration " + i);
// imitating time consuming code
Thread.Sleep(1000);
}
});
Console.WriteLine("Exiting DoWork()");
}
}
Output:
Entered DoWork(). Sleeping 3
async task iteration 0
Task status: WaitingForActivation
Waiting for ENTER
async task iteration 1
async task iteration 2
async task iteration 3
async task iteration 4
async task iteration 5
async task iteration 6
async task iteration 7
async task iteration 8
async task iteration 9
Exiting DoWork()

- 6,175
- 3
- 37
- 61
-
You are correct in that `await` doesn't pause anything, but it can make sense to think that it does. The accepted answer has pause in quotes, implying that it's not true, it's just a way of thinking about what's going on. I'd say it's not really wrong, but it's certainly not well explained. As for not being in a method marked `async`, at the time that post was written the feature hadn't yet been released, and the syntax for it hadn't even been invented yet. Explaining the syntax now that it has is fine, just understand why it's not in that answer. – Servy Feb 15 '13 at 15:54
-
As to this answer, why are you using `Thread.Sleep` in your async task? You really shouldn't be using a blocking method like that. They should be replaced with `await Task.Delay(X000);` instead, unless you're trying to demonstrate something by including them, in which case, please explain what you're trying to show by mixing async and non-async operations in that method. – Servy Feb 15 '13 at 15:56
-
-
@Servy 2. just imitating time-consuming code to demonstrate execution order – Anri Feb 15 '13 at 15:58
-
If that's what your intent is then you should add a comment next to each `Sleep` to indicate that, something like "placeholder for real work" or something like that. Also, if you have CPU bound work that will run for 3 seconds (the first sleep) it shouldn't be in the current context, it should be inside of an `await Task.Run(...` like the following example. – Servy Feb 15 '13 at 16:00
-
-
1You're also aware that it will block the caller for 3 seconds before it even gives them the task that they can `await` on? Meaning if this is called from a UI thread it will block the UI thread for 3 seconds? The idea of this model is to avoid doing things like that. – Servy Feb 15 '13 at 16:05
-
1@Servy yes, that was the point. To show all the stages of execution. This is not a real-world example. – Anri Feb 15 '13 at 16:06
-
1If you're going to demonstrate things that you shouldn't do it's best to state that they shouldn't be done and why. As it is, readers of your answer might think this is code worth imitating in spirit. – Servy Feb 15 '13 at 16:08
-
7
-
2
-
2@ Anri ...I really appreciate your efforts here. Thanks a lot!! – Praveen Prajapati Aug 21 '13 at 09:24
-
When there's a return type `Task`, caller expects the async method not to block. So, a `Thread.Sleep()` like action in an async method is actually just bad design. If you have an async method, you must make sure it's actually async. That is hand `Task` back to the caller without blocking. – kovac Nov 28 '18 at 07:32
For anyone new to asynchronous programming in .NET, here's a (totally fake) analogy in a scenario you may be more familiar with - AJAX calls using JavaScript/jQuery. A simple jQuery AJAX post looks like this:
$.post(url, values, function(data) {
// AJAX call completed, do something with returned data here
});
The reason we process the results in a callback function is so we don't block the current thread while waiting for the AJAX call to return. Only when the response is ready will the callback get fired, freeing the current thread to do other things in the mean time.
Now, if JavaScript supported the await
keyword (which of course it doesn't (yet!)), you could achieve the same with this:
var data = await $.post(url, values);
// AJAX call completed, do something with returned data here
That's a lot cleaner, but it sure looks like we introduced synchronous, blocking code. But the (fake) JavaScript compiler would have taken everything after await
and wired it into a callback, so at runtime the second example would behave just like the first.
It may not seem like it's saving you much work, but when it comes to things like exception handling and synchronization contexts, the compiler is actually doing a lot of heavy lifting for you. For more, I'd recommend the FAQs followed by Stephen Cleary's blog series.

- 37,557
- 17
- 150
- 173
-
Sticking with this fake analogy (which helped me a great deal btw, so thanks!), what do you mean "everything after"? Everything within the scope of the same function (method) only? Or everything after it as in anything at all that could have been added to the call stack? – Jun 19 '15 at 08:47
-
2"Everything after" = the rest of the method. The compiler effectively re-writes the rest of the method as a callback and control returns immediately to the current method's caller. – Todd Menier Jun 19 '15 at 18:45
-
1Brilliant Todd, thanks again for your explanation. Useful to others too I'm sure. – Jun 19 '15 at 20:04
If I had to implement it in Java it would look some thing like this:
/**
* @author Ilya Gazman
*/
public abstract class SynchronizedTask{
private ArrayList<Runnable> listeners = new ArrayList<Runnable>();
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 6, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1000));
public final void await(Runnable listener){
synchronized (this) {
listeners.add(listener);
}
}
public void excecute(){
onExcecute();
for (int i = listeners.size() - 1; i >= 0; i--) {
Runnable runnable;
synchronized (this) {
runnable = listeners.remove(i);
}
threadPoolExecutor.execute(runnable);
}
}
protected abstract void onExcecute();
}
Your application would use it like this:
public class Test{
private Job job = new Job();
public Test() {
craeteSomeJobToRunInBackground();
methode1();
methode2();
}
private void methode1(){
System.out.println("Running methode 1");
job.await(new Runnable() {
@Override
public void run() {
System.out.println("Continue to running methode 1");
}
});
}
private void methode2(){
System.out.println("Running methode 2");
}
private void craeteSomeJobToRunInBackground() {
new Thread(new Runnable() {
@Override
public void run() {
job.excecute();
}
}).start();
}
private class Job extends SynchronizedTask{
@Override
protected void onExcecute() {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Job is done");
}
}
}

- 31,250
- 24
- 137
- 216