Appendix C. Asynchronous and Multithreaded WPF Programming

If you like to write applications that annoy your users, a good way to do this is to make the user interface stop responding to input from time to time. For extra frustration, you can compound the problem by not giving any visible indication that work might be progressing, leaving the user to wonder whether the application is busy or has simply crashed. Because you'll get this behavior by default if you don't take certain steps to maintain responsiveness, you can stop reading now. Unless, that is, you'd prefer not to annoy your users.

Unfortunately, it's all too easy to write your application in such a way that it becomes unresponsive when it performs time-consuming work such as accessing a server over a network or reading files off disk. In Windows, all messages regarding user input for a particular window are delivered to the same thread. In general, this is a good thing, because it means your code has to deal with input events only one at a time, and does not have to worry about thread safety. The downside is that the application can respond to input only if this thread is available to process it.

Many APIs are synchronous—they do not return until they have completed the work you asked them to perform. (Such APIs are said to block.) If you write a handler for a button's Click event that makes a synchronous API call to retrieve data from a database, that call will not return until the database returns the data. The thread ...

Get Programming WPF, 2nd Edition 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.