Asynchronous Programming in C# 5.0 part two: Whence await?

Asynchronous Programming in C# 5.0 part two: Whence await?

Rate This

I want to start by being absolutely positively clear about two things, because our usability research has shown this to be confusing. Remember our little program from last time?

async void ArchiveDocuments(List<Url> urls)
{
  Task archive = null;
  for(int i = 0; i < urls.Count; ++i)
  {
    var document = await FetchAsync(urls[i]);
    if (archive != null)
      await archive;
    archive = ArchiveAsync(document);
  }
}

The two things are:

1) The “async” modifier on the method does not mean “this method is automatically scheduled to run on a worker thread asynchronously”. It means the opposite of that; it means “this method contains control flow that involves awaiting asynchronous operations and will therefore be rewritten by the compiler into continuation passing style to ensure that the asynchronous operations can resume this method at the right spot.” The whole point of async methods it that you stay on the current thread as much as possible. They’re like coroutines: async methods bring single-threaded cooperative multitasking to C#. (At a later date I’ll discuss the reasons behind requiring the async modifier rather than inferring it.)

2) The “await” operator used twice in that method does not mean “this method now blocks the current thread until the asynchronous operation returns”. That would be making the asynchronous operation back into a synchronous operation, which is precisely what we are attempting to avoid. Rather, it means the opposite of that; it means “if the task we are awaiting has not yet completed then sign up the rest of this method as the continuation of that task, and then return to your caller immediately; the task will invoke the continuation when it completes.

It is unfortunate that people’s intuition upon first exposure regarding what the “async” and “await” contextual keywords mean is frequently the opposite of their actual meanings. Many attempts to come up with better keywords failed to find anything better. If you have ideas for a keyword or combination of keywords that is short, snappy, and gets across the correct ideas, I am happy to hear them. Some ideas that we already had and rejected for various reasons were:

wait for FetchAsync(…)
yield with FetchAsync(…)
yield FetchAsync(…)
while away the time FetchAsync(…)
hearken unto FetchAsync(…)
for sooth Romeo wherefore art thou FetchAsync(…)

Moving on. We’ve got a lot of ground to cover. The next thing I want to talk about is “what exactly are those ‘thingies’ that I handwaved about last time?”

Last time I implied that the C# 5.0 expression

document = await FetchAsync(urls[i])

gets realized as:

state = State.AfterFetch;
fetchThingy = FetchAsync(urls[i]);
if (fetchThingy.SetContinuation(archiveDocuments))
  return;
AfterFetch: ;
document = fetchThingy.GetValue();

what’s the thingy?

In our model for asynchrony an asynchronous method typically returns a Task<T>; let’s assume for now that FetchAsync returns a Task<Document>. (Again, I’ll discuss the reasons behind this "Task-based Asynchrony Pattern" at a later date.) The actual code will be realized as:

fetchAwaiter = FetchAsync(urls[i]).GetAwaiter();
state = State.AfterFetch;
if (fetchAwaiter.BeginAwait(archiveDocuments))
  return;
AfterFetch: ;
document = fetchAwaiter.EndAwait();

The call to FetchAsync creates and returns a Task<Document> - that is, an object which represents a “hot” running task. Calling this method immediately returns a Task<Document> which is then somehow asynchronously fetches the desired document. Perhaps it runs on another thread, or perhaps it posts itself to some Windows message queue on this thread that some message loop is polling for information about work that needs to be done in idle time, or whatever. That’s its business. What we know is that we need something to happen when it completes. (Again, I’ll discuss single-threaded asynchrony at a later date.)

To make something happen when it completes, we ask the task for an Awaiter, which exposes two methods. BeginAwait signs up a continuation for this task; when the task completes, a miracle happens: somehow the continuation gets called. (Again, how exactly this is orchestrated is a subject for another day.) If BeginAwait returns true then the continuation will be called; if not, then that’s because the task has already completed and there is no need to use the continuation mechanism.

EndAwait extracts the result that was the result of the completed task.

We will provide implementations of BeginAwait and EndAwait on Task (for tasks that are logically void returning) and Task<T> (for tasks that return a value). But what about asynchronous methods that do not return a Task or Task<T> object? Here we’re going to use the same strategy we used for LINQ. In LINQ if you say

from c in customers where c.City == "London" blah blah blah

then that gets translated into

customers.Where(c=>c.City=="London") …

and overload resolution tries to find the best possible Where method by checking to see if customers implements such a method, or, if not, by going to extension methods. The GetAwaiter / BeginAwait / EndAwait pattern will be the same; we’ll just do overload resolution on the transformed expression and see what it comes up with. If we need to go to extension methods, we will.

Finally: why "Task"?

The insight here is that asynchrony does not require parallelism, but parallelism does require asynchrony, and many of the tools useful for parallelism can be used just as easily for non-parallel asynchrony. There is no inherent parallelism in Task; that the Task Parallel Library uses a task-based pattern to represent units of pending work that can be parallelized does not require multithreading.

As I've pointed out a few times, from the point of view of the code that is waiting for a result it really doesn't matter whether that result is being computed in idle time on this thread, in a worker thread in this process, in another process on this machine, on a storage device, or on a machine halfway around the world. What matters is that it's going to take time to compute the result, and this CPU could be doing something else while it is waiting, if only we let it.

The Task class from the TPL already has a lot of investment in it; it's got a cancellation mechanism and other useful features. Rather than invent some new thing, like some new "IFuture" type, we can just extend the existing task-based code to meet our asynchrony needs.

Next time: How to further compose asynchronous tasks.

  • As usual, Jon Skeet has nailed it on the head. Some variation of 'continue' or 'yield' seems most appropriate ('yield until' definitely has the right ring to it).

  • @LBushkin: Yes, it shouldn't be a problem. You write a GetAwaiter() extension method for IAsyncResult, which returns something with BeginAwait(Action) and EndAwait().

    That's the beauty of it being a *pattern* rather than a specific type. The only ties to Task that I'm aware of are that an async method/anonymous function will always return a Task or Task<T>. I don't believe the way that that task is constructed is specified.

  • @Juozas, async doesn't imply threading. It could be async kernel IO, Windows messages, etc, that are providing the asynchrony.

  • @Juozas: Using "threaded" would *definitely* be the wrong word, IMO. It means there's a natural assumption that extra threads are involved, when they may well not be. For example, when you issue an asynchronous IO request, that doesn't require an extra thread to be running. You can have many, many asynchronous requests in flight at a time, using IO completion ports but not extra threads and the stack space hit incurred by those threads.

  • Does a simple 'defer' work?

       var document = defer FetchAsync(urls[i]);

    "defer" is sort like saying "I'll take care of this later"...

  • I haven't had a chance to play with the CTP yet, but it occurs to me that one construct that may be complicated by CPS-based asynchrony is using( ). How does something like this translate into a state machine:

       using( var conn = AcquireConnection() )

       {

            await SomeAsyncWork( conn );

       }

    What happens to deterministic disposal with exception occur, or cancellation is performed?

  • I find myself turning the await statement into something like a using block which I find much clearer. I think the problem I have is not the keyword but seeing the different code blocks that will be executed. This seems much less upside down and inside out.

    async void ArchiveDocuments(List<Url> urls)

    {

     Task archive = null;

     for(int i = 0; i < urls.Count; ++i)

     {

       await (var document = FetchAsync(urls[i])

       {

           await(archive == null || archive)

           {

               archive = ArchiveAsync(document);

           }

        }

     }

    }

  • async void ArchiveDocuments(List<Url> urls)

    {

     Task archive = null;

     for(int i = 0; i < urls.Count; ++i)

     {

       var document =  upon FetchAsync(urls[i]);

       if (archive != null)

         upon archive;

       archive = ArchiveAsync(document);

     }

    }

    Thoughts?

  • As others have noted, the connection with yield might be helpful, so how about: yield resume. This keyword combo this indicates that it behaves like enumerators by yielding immediately, and the "resume" implies a resumption from that point.

  • The obvious choice would be to split await between let!, do! & using!.

    Though, snark aside, it just struck me - I've not seen anything covering the "using!" scenarios yet.

  • "hearken unto" is definitely the best one so far. That would bring C# to the pinnacle of awesomeness.

  • async is pretty fine - it's established in F# and rather convenient.

    @Blake let!, do! & using! are similar, but not the same - so it can be bewilder to those, who got used to the original )

    I agree with Jon Skeet - maybe there's should be smth with 'continue'...

    Hey, await isn't so bad thanks to its compactness. Continue...After... to long to such keyword

  • I want to put in my vote for the "continue after" syntax.  When I'm writing async code I tend to think of the control flow as a queue of operations (even though, strictly speaking, it's more like a pipeline).  The phrase "continue after" unambiguously says "schedule the rest of this stuff after X in the queue".

    It's far better than both "yield" and "await" in the sense that those two statements imply, well, *waiting*, which we might not actually be doing.  The phrase "continue after" doesn't, necessarily imply a wait; it should be intuitive that if the thing before us in the queue is already finished, then we're going to plow on ahead.

  • Cool stuff!! What about one of these?

    yield completed AsyncFetch(…)

    yield future AsyncFetch(…)

    future AsyncFetch(…)

    yield defer AsyncFetch(…)

    defer AsyncFetch(…)

  • How about

    stop; FetchAsync(...) time;

Page 3 of 11 (161 items) 12345»