- Most objects in WPF derive from DispatcherObject, which provides the basic constructs for dealing with concurrency and threading.
- It is the base class for any object that wishes to be accessed only on the thread that created it
- WPF is based on a messaging system implemented by the dispatcher
- WPF dispatcher uses User32 messages for performing cross thread calls.
- Thread affinity happens when a component uses the identity of the executing thread to store some type of state. The most common form of this is to use the thread local store (TLS) to store state. Thread affinity requires that each logical thread of execution be owned by only one physical thread in the operating system, which can become memory intensive. In the end, WPF’s threading model was kept in sync with the existing User32 threading model of single threaded execution with thread affinity.
- WPF requires Single Threaded Apartment (STA) threading, so you must apply a [System.STAThread()] attribute to your Main method.
- The dispatcher is a basic message dispatching system, with multiple prioritized queues. Examples of messages include raw input notifications (mouse moved), framework functions (layout), or user commands (execute this method).
- DispatcherObject defines a Dispatcher property (of type Dispatcher) containing several overloads of Invoke (a synchronous call) and BeginInvoke (an asynchronous call).
- BeginInvoke has no corresponding EndInvoke
- To know when an async operation is finished we can use DispatcherOperation class
- Dispatcher.BeginInvoke method returns a DispatcherOperation object
- Status property of type DispatcherOperationStatus enumeration (Pending, Executing, Completed, Aborted)
- DispatcherOperation.Abort method
- CheckAccess method returns true if you are on the correct thread, false otherwise.
- VerifyAccess method is intended for when you think you are already on the right thread, and it would be indicative of a problem in the program if you were not.
- It throws an exception if you are on the wrong thread.
- It used by many WPF type when they are used
- The Dispatcher class:
- it lives in the System.Windows.Threading namespace
- it defines a Dispatcher property, which returns the Dispatcher object for the thread to which the object belongs
- Dispatcher.CurrentDispatcher static property
- Dispatcher.Wait method: wait for the operation to complete
References:Chris Sells and Ian Griffiths, "Programming WPF", SECOND EDITION, O’Reilly Media
Adam Nathan, "Windows Presentation Foundation Unleashed", Sams Publishing