Multiple Awaits in a single method

async-await, asynchronous, c#

Solution

You can think of `await` as "pausing" the `async` method until that operation is complete. As a special case, if the operation is already completed (or is extremely fast), then the `await` will not "pause" the method; it will continue executing immediately.

So in this case (assuming that `WriteStartDocumentAsync` is not already completed), `await` will pause the method and return an uncompleted task to the caller. Note that the `Task` returned by an `async` method represents that method; when the method completes, then that `Task` is completed.

Eventually, `WriteStartDocumentAsync` will complete, and that will schedule the rest of the `async` method to continue running. In this case, it'll execute the next part of the method until the next `await`, when it gets paused again, etc. Eventually, the `async` method will complete, which will complete the `Task` that was returned to represent that method.

For more information, I have an `async`/`await` intro on my blog.

Problem

I have a method like this: ``` public static async Task SaveAllAsync() { foreach (var kvp in configurationFileMap) { using (XmlWriter xmlWriter = XmlWriter.Create(kvp.Value, XML_WRITER_SETTINGS)) { FieldInfo[] allPublicFields = kvp.Key.GetFields(BindingFlags.Public | BindingFlags.Static); await xmlWriter.WriteStartDocumentAsync(); foreach (FieldInfo fi in allPublicFields) { await xmlWriter.WriteStartElementAsync("some", "text", "here"); } await xmlWriter.WriteEndDocumentAsync(); } } } ``` But I'm struggling to follow what will happen when someone calls `SaveAllAsync()`. What I think will happen is this: - When someone first calls it, `SaveAllAsync()` will return control to the caller at the line `await xmlWriter.WriteStartDocumentAsync();` - Then... When they await `SaveAllAsync()` (or wait for the task)... What happens? Will `SaveAllAsync()` still be stuck on the first await until that is called? Because there's no threading involved, I guess that is the case...

Original source