Chapter 21. Threading

 

This chapter covers:

  • The Dispatcher
  • Asynchronous calls
  • Timers
  • Making our CIA application more insulting

In Windows Forms, the cardinal rule for threading was that all UI operations had to take place on the same thread—or, at least, on the thread that created the window with which you were working. Although the mechanics are a little bit different, the same exact rule applies to WPF.

WPF has two UI threads: the main UI thread and a rendering thread, which does the real rendering, animation, and so on. But, you can almost never interact with the rendering thread; for practical purposes, you can ignore it. In threading situations, you have to make sure that all your UI calls take place on the main UI thread.

There are a several reasons why you might want to use threads within your application. The biggies are:

  • ResponsivenessSo that your application doesn’t appear to lock up while operations take place
  • Handling slow operationsSo that users can work on other things while slow ops, such as queries, take place

While discussing threading in general, we’ll also demonstrate how to make asynchronous calls with WPF and to use the new DispatchTimer mechanism.

21.1. Moving slow work into a background thread

21.2. Asynchronous calls

21.3. Timers

21.4. Summary