0

I'm imagining that if I write code like this:

private async void button1_Click(object sender, EventArgs e)
{
   this.button1.Enabled = false; 
   var someTask = Task<int>.Factory.StartNew(() => slowFunc(1, 2)); 
   await someTask;  
   this.label1.Text = "Result: " + someTask.Result.ToString(); 
   this.button1.Enabled = true;
}

That the compiler actually does this:

private async void button1_Click(object sender, EventArgs e)
{
   this.button1.Enabled = false; 
   var someTask = Task<int>.Factory.StartNew(() => slowFunc(1, 2)); 
   save_context_including_someTask();
   when_someTask_completes(post_message_into_queue(run_afterStuff()));
}
private void afterStuff()
{
   restore_context_including_someTask();
   this.label1.Text = "Result: " + someTask.Result.ToString(); 
   this.button1.Enabled = true;
}

So it uses the (normally hidden) message queue to execute the code after the "await" in a synchronous manner (it doesn't interrupt anything I'm already doing on the UI thread). Yes?

But then the implementation of async/await must be rather different, if I run them in a thread besides the main UI thread, where there isn't a message queue.

Since there isn't any way for the compiler to know what the "next thing" is in my non-UI thread, when it hits an "await" it must just .... stop and wait?

To make a long question shorter, is await synchronous in a non-UI thread?

Betty Crokker
  • 3,001
  • 6
  • 34
  • 68
  • No it is not syncronous, when you are not on the UI thread `save_context_including_someTask()` will grab the default [`SynchronizationContext`](https://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext(v=vs.110).aspx) which will make `post_message_into_queue(` use the ThreadPool queue. – Scott Chamberlain Mar 07 '17 at 17:37
  • 1
    See [this old answer of mine](http://stackoverflow.com/questions/20573625/how-does-async-await-not-block/20573825#20573825) which shows a more realistic conversion of what async/await code gets turned in to, going from a simple abstraction all the way down to the actual code the compiler generates. – Scott Chamberlain Mar 07 '17 at 17:41

0 Answers0