Now let's write a button click handler using await
and see what has changed:
private static async void Click(object sender, EventArgs e) { _label.Content = "Starting asynchronous operation...."; await SomeOperationAsync(); _label.Content = "Asynchronous operation complete!"; }
Once again, without knowing exactly what SomeOperationAsync
is, it is still impossible to know how this code is going to behave. Imagine the simplest asynchronous method implementation:
static Task SomeOperationAsync() { return Task.Delay(TimeSpan.FromSeconds(5)); }
In this case, the program will run successfully, which means that the continuation code runs on the UI thread. To find out how this happens, we need to review two important abstractions: execution and synchronization contexts.