Common problems and solutions

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) ...

Get Mastering C# Concurrency now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.