16

I heard somewhere that C# 5 async-await will be so awesome that you will not have to worry about doing this:

if (InvokeRequired)
{
    BeginInvoke(...);
    return;
}
// do your stuff here

It looks like the callback of a await operation will happen in the original thread of the caller. It has been stated several times by Eric Lippert and Anders Hejlsberg that this feature originated from the need to make UIs (particularly touch device UIs) more responsive.

I think a common usage of such feature would be something like this:

public class Form1 : Form
{
    // ...
    async void GetFurtherInfo()
    {
        var temperature = await GetCurrentTemperatureAsync();
        label1.Text = temperature;
    }
}

If only a callback is used then setting the label text will raise an exception because it's not being executed in the UI's thread.

So far I couldn't find any resource confirming this is the case. Does anyone know about this? Are there any documents explaining technically how this will work?

Please provide a link from a reliable source, don't just answer "yes".

2
  • This seems highly unlikely, at least insofar as the await functionality is concerned. It's just a lot of syntactic sugar for continuation passing. Possibly there are some other unrelated improvements to WinForms that are supposed to help? That would fall under the .NET framework itself, though, and not C# specifically.
    – Aaronaught
    Commented Oct 16, 2011 at 16:18
  • @Aaronaught I agree, this is why I'm asking the question precisely. I edited the question to make clear where I'm coming from. Sounds weird that they would create this feature and still require that we use the infamous InvokeRequired style of code.
    – Alex
    Commented Oct 16, 2011 at 16:48

3 Answers 3

18

I think you're getting a few things confused, here. What you're asking for is already possible using System.Threading.Tasks, the async and await in C# 5 are just going to provide a little nicer syntactic sugar for the same feature.

Let's use a Winforms example - drop a button and a textbox on the form and use this code:

private void button1_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew<int>(() => DelayedAdd(5, 10))
        .ContinueWith(t => DelayedAdd(t.Result, 20))
        .ContinueWith(t => DelayedAdd(t.Result, 30))
        .ContinueWith(t => DelayedAdd(t.Result, 50))
        .ContinueWith(t => textBox1.Text = t.Result.ToString(),
            TaskScheduler.FromCurrentSynchronizationContext());
}

private int DelayedAdd(int a, int b)
{
    Thread.Sleep(500);
    return a + b;
}

Run it and you'll see that (a) it doesn't block the UI thread and (b) you don't get the usual "cross-thread operation not valid" error - unless you remove the TaskScheduler argument from the last ContinueWith, in which case you will.

This is bog-standard continuation passing style. The magic happens in the TaskScheduler class and specifically the instance retrieved by FromCurrentSynchronizationContext. Pass this into any continuation and you tell it that the continuation must run on whichever thread called the FromCurrentSynchronizationContext method - in this case, the UI thread.

Awaiters are slightly more sophisticated in the sense that they're aware of which thread they started on and which thread the continuation needs to happen on. So the above code can be written a little more naturally:

private async void button1_Click(object sender, EventArgs e)
{
    int a = await DelayedAddAsync(5, 10);
    int b = await DelayedAddAsync(a, 20);
    int c = await DelayedAddAsync(b, 30);
    int d = await DelayedAddAsync(c, 50);
    textBox1.Text = d.ToString();
}

private async Task<int> DelayedAddAsync(int a, int b)
{
    Thread.Sleep(500);
    return a + b;
}

These two should look very similar, and in fact they are very similar. The DelayedAddAsync method now returns a Task<int> instead of an int, and so the await is just slapping continuations onto each one of those. The main difference is that it's passing along the synchronization context on each line, so you don't have to do it explicitly like we did in the last example.

In theory the differences are a lot more significant. In the second example, every single line in the button1_Click method is actually executed in the UI thread, but the task itself (DelayedAddAsync) runs in the background. In the first example, everything runs in the background, except for the assignment to textBox1.Text which we've explicitly attached to the UI thread's synchronization context.

That's what's really interesting about await - the fact that an awaiter is able to jump in and out of the same method without any blocking calls. You call await, the current thread goes back to processing messages, and when it's done, the awaiter will pick up exactly where it left off, in the same thread it left off in. But in terms of your Invoke/BeginInvoke contrast in the question, I'm sorry to say that you should have stopped doing that a long time ago.

17
  • That's very interesting @Aaronaught. I was aware of the continuation passing style but wasn't aware of this whole "synchronization context" thing. Is there any document linking this sync context to C# 5 async-await? I understand it's an existing feature but the fact they are using it by default sounds like a big deal, specially because it must have some major impacts in performance, right? Any further comments on that? Thanks for your answer by the way.
    – Alex
    Commented Oct 16, 2011 at 20:00
  • 1
    @Alex: For answers to all of those follow-up questions, I suggest you read Async Performance: Understanding the Costs of Async and Await. The "Care About Context" section explains how it all relates to synchronization context.
    – Aaronaught
    Commented Oct 16, 2011 at 20:06
  • 2
    I'm wondering why there is a lot of discussions on using InvokeRequired style still and most of the threads I've seen don't even mention sync contexts. It would have saved me the time to put this question up...
    – Alex
    Commented Oct 16, 2011 at 20:49
  • 2
    @Alex: I guess you weren't looking in the right places. I don't know what to tell you; there are large parts of the .NET community which take a long time to catch up. Hell, I still see some coders using the ArrayList class in new code. I still barely have any experience with RX, myself. People learn what they need to know and share what they already know, even if what they already know is out of date. This answer might be out of date in a few years.
    – Aaronaught
    Commented Oct 16, 2011 at 21:37
  • 1
    Sync contexts are a bit harder to explain/grok, evidenced by a minor error in your answer: the default sync context of the thread pool executes callbacks on the thread pool in general, not necessarily "on whichever thread called the FromCurrentSynchronizationContext method". Potentially an important distinction if you're accessing thread local storage! Commented Dec 18, 2012 at 22:29
4

Yes, for the UI thread, the callback of a await operation will happen on the original thread of the caller.

Eric Lippert wrote an 8-part series all about it a year ago: Fabulous Adventures In Coding

EDIT: and here's Anders' //build/ presentation: channel9

BTW, did you notice that if you turn "//build/" upside down, you get "/plinq//" ;-)

3

Jon Skeet gave an excellent presentation covering Async methods in C#5 which you may find extremely useful:

http://skillsmatter.com/podcast/home/async-methods

1
  • EduAsync by the same author may also be a good source of information about Async.
    – Matthieu
    Commented Dec 17, 2011 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.