To see what can happen if we do not control how exactly the code correlates to threads, let's start with a simple WPF application that has three different buttons. In this particular case, it is not relevant how the WPF application gets created and how we compose UI controls, so we are going to concentrate on the code inside the button click handlers. All the code for this sample is located in the AsyncInUI project in the samples for Chapter 9. Besides this, we will not use async
and await
yet, because they will create one more abstraction level and thus make the code harder to understand.
The first button tries to call a Task
returning method synchronously:
private static void SyncClick(object sender, EventArgs e) { _label.Content = string.Empty; try { string result = TaskMethod().Result; _label.Content = result; } catch (Exception ex) { _label.Content = ex.Message; } }
Without knowing exactly what TaskMethod...