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?