Archive for the ‘WPF’ Category

Dependency Properties in WPF

August 19, 2012 1 comment


When you begin to develop appliations with WPF, you will soon stumble across DependencyProperties. They look quite similar to normal .NET properties, but the concept behind is much more complex and powerful.

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

The advantages of dependency properties are

Reduced memory footprint
It’s a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The default values are stored once within the dependency property.

Value inheritance
When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it applies to all textblocks below except you override the value.

Change notification
Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you get notified, when the value of the property has been changed. This is also used by the databinding.

Value resolution strategy

Every time you access a dependency property, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not if a custom style trigger is active,… and continues until it founds a value. At last the default value is always available.
The magic behind it

Each WPF control registers a set of DependencyProperties to the static DependencyProperty class. Each of them consists of a key – that must be unique per type – and a metadata that contain callbacks and a default value.

All types that want to use DependencyProperties must derive from DependencyObject. This baseclass defines a key, value dictionary that contains local values of dependency properties. The key of an entry is the key defined with the dependency property.
When you access a dependency property over its .NET property wrapper, it internally calls GetValue(DependencyProperty) to access the value. This method resolves the value by using a value resolution strategy that is explained in detail below. If a local value is available, it reads it directly from the dictionary. If no value is set if goes up the logical tree and searches for an inherited value. If no value is found it takes the default value defined in the property metadata. This sequence is a bit simplified, but it shows the main concept.

Value Changed Callback

The change notification callback is a static method, that is called everytime when the value of the TimeProperty changes. The new value is passed in the EventArgs, the object on which the value changed is passed as the source.

private static void OnCurrentTimePropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
MyClockControl control = source as MyClockControl;
DateTime time = (DateTime)e.NewValue;
// Put some update logic here…

Readonly DependencyProperties

Some dependency property of WPF controls are readonly. They are often used to report the state of a control, like the IsMouseOver property. Is does not make sense to provide a setter for this value.

Maybe you ask yourself, why not just use a normal .NET property? One important reason is that you cannot set triggers on normal .NET propeties.

Creating a read only property is similar to creating a regular DependencyProperty. Instead of calling DependencyProperty.Register() you call DependencyProperty.RegisterReadonly(). This returns you a DependencyPropertyKey. This key should be stored in a private or protected static readonly field of your class. The key gives you access to set the value from within your class and use it like a normal dependency property.

Second thing to do is registering a public dependency property that is assigned to DependencyPropertyKey.DependencyProperty. This property is the readonly property that can be accessed from external.

// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey =
typeof(bool), typeof(MyClass),
new FrameworkPropertyMetadata(false));

// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty =

// .NET Property wrapper
public int IsMouseOver
get { return (bool)GetValue(IsMouseoverProperty); }
private set { SetValue(IsMouseOverPropertyKey, value); }

Listen to dependency property changes

If you want to listen to changes of a dependency property, you can subclass the type that defines the property and override the property metadata and pass an PropertyChangedCallback. But an much easier way is to get the DependencyPropertyDescriptor and hookup a callback by calling AddValueChanged()

DependencyPropertyDescriptor textDescr = DependencyPropertyDescriptor.
FromProperty(TextBox.TextProperty, typeof(TextBox));

if (textDescr!= null)
textDescr.AddValueChanged(myTextBox, delegate
// Add your propery changed logic here…

Problem with Dependency Properties

1. Some people argues that the use of DependencyProperties the code extremely ugly. I myself think that this is exaclty the same.
2. DependencyObjects are not marked as serializable
3. A DependencyObject has thread affinity – it can only be accessed on the thread on which it was created


Attached Properties


Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know anything about this value.

A good example for this concept are layout panels. Each layout panel needs different data to align its child elements. The Canvas needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it’s not possible to have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control that needs the data from another control in a specific context. For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:

<Button Canvas.Top=”20″ Canvas.Left=”20″ Content=”Click me!”/>

public static readonly DependencyProperty TopProperty =
typeof(double), typeof(Canvas),
new FrameworkPropertyMetadata(0d,

public static void SetTop(UIElement element, double value)
element.SetValue(TopProperty, value);

public static double GetTop(UIElement element)
return (double)element.GetValue(TopProperty);

How to clear a local value

Because null is also a valid local value, there is the constant DependencyProperty.UnsetValue that describes an unset value.

button1.ClearValue( Button.ContentProperty );

Categories: WPF Tags:

WPF Custom Control

August 12, 2012 2 comments

The differences between CustomControls and UserControls

WPF has two concepts of controls: UserControls and CustomControls. But what’s the difference between them? In this article I try to list the characteristics of each of them to help you to choose the right type for your project.

UserControl (Composition)

  • Composes multiple existing controls into a reusable “group”
  • Consists of a XAML and a code behind file
  • Cannot be styled/templated
  • Derives from UserControl

This example of an “RGB user control” composes three labels and textboxes as well as a color field together to an reusable part. The logic in the code behind file adds a Color DependencyProperty that gets and sets the resolved color.

CustomControl (Extending an existing control)

  • Extends an existing control with additional features
  • Consists of a code file and a default style in Themes/Generic.xaml
  • Can be styled/templated
  • The best approach to build a control library

This example of a “Numeric up/down” control is an extension of a textbox. The up and down buttons are defined in the default template of the control and wired up in the OnApplyTemplate() override in the logic part of the control. The ControlTemplate can easily be exchanged by another that has the up,down buttons aligned left for example.

How to Create a WPF Custom Control

Step 1: Open VS 2010 and create a blank solution and  name it as ‘WPF_CustomControl’..

Step 2: To this solution, add a new WPF Custom Control Library Project and name it as ‘WPF40_FileUploadCustomControl’. This project will have ‘Themes’ folder containing ‘Generic.Xaml’. Also this project will contain ‘CustomControl1.cs’ code file. This file will contain necessary business logic of the control.

Step 3: Rename ‘CustomControl1.cs’ to ‘FileUploadCustomControl.cs’. Add the following code in ‘Generic.xaml’:


    <Style TargetType=”{x:Type local:FileUploadCustomControl}”>
        <Setter Property=”Template”>
                <ControlTemplate TargetType=”{x:Type local:FileUploadCustomControl}”>
                    <Border Background=”{TemplateBinding Background}”
                            BorderBrush=”{TemplateBinding BorderBrush}”
                            BorderThickness=”{TemplateBinding BorderThickness}”>
                        <StackPanel Orientation=”Horizontal”
                            <TextBox Name=”TXT_FILE_NAME” Width=”150″></TextBox>
                            <Button Name=”BTN_BROWSE_FILE” Width=”50″Content=”Browse”></Button>
The above code defines only the control template which contains ‘StackPanel’, ‘TextBox’ and ‘Button’ visual elements. One important here is that since this is just a resource dictionary, you cannot define any event on the elements.
Step 4: Now it’s time to define the business logic. Make sure that in the ‘FileUploadCustomControl.cs’ file, the class ‘CustomControl1’ is renamed to ‘FileUploadCustomControl’. Also rename the constructor. The code in the constructor will be as below:
static FileUploadCustomControl()
Define TextBox and Button at class level as shown below. This will be instantiated using the controls names set in the template XAML above in Step 3.
TextBox txtFileName = null;
Button btnBrowse = null;
Since this control is used to upload the image and this will be displayed in the container of this control, I have declared the following dependency property name ‘FileName’.
public string FileName
    get { return (string)GetValue(FileNameProperty); }
    set { SetValue(FileNameProperty, value); }
// Using a DependencyProperty as the backing store for FileName. This enables animation, styling, binding, etc…
public static readonly DependencyProperty FileNameProperty =
    DependencyProperty.Register(“FileName”, typeof(string),typeof(FileUploadCustomControl),
        new FrameworkPropertyMetadata(string.Empty,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
Since the control has to expose the ‘FileName’ property to its container application, the CC should declare the following routed event:
public event RoutedEventHandler FileNameChanged
    add { AddHandler(FileNameChangedEvent, value); }
    remove { RemoveHandler(FileNameChangedEvent, value); }
public static readonly RoutedEvent FileNameChangedEvent =
    RoutingStrategy.Bubble, typeof(RoutedEventHandler),typeof(FileUploadCustomControl));
Now it’s time to construct the control, so override ‘OnApplyTemplate()’ method as below:
public override void OnApplyTemplate()
    txtFileName = this.Template.FindName(“TXT_FILE_NAME”, this) as TextBox;
    btnBrowse = this.Template.FindName(“BTN_BROWSE_FILE”, this) as Button;
    btnBrowse.Click += new RoutedEventHandler(btnBrowse_Click);
    txtFileName.TextChanged += new TextChangedEventHandler(txtFileName_TextChanged);
The above method shows how the Button and TextBox objects are created using the respective control name from the ‘Generic.xaml’.
Write the following code in the Browse button event. This code will launch the open dialog box and then the file can be selected.
void btnBrowse_Click(object sender, RoutedEventArgs e)
    OpenFileDialog fileDIalog = new OpenFileDialog();
    fileDIalog.Filter = “Image files (*.bmp, *.jpg)|*.bmp;*.jpg|Doc Files (*.doc;*.docx)|*.doc;*.docx”;
    fileDIalog.AddExtension = true;
    if (fileDIalog.ShowDialog() == true)
        FileName = fileDIalog.FileName;
        txtFileName.Text = FileName;
Write the following code in the TextChanged event of the textbox, here e.Handled = True’ will stop the event at the control level itself and the ‘FileNameChanged’ is raised. This event is then handled in the container WPF application.
void txtFileName_TextChanged(object sender, TextChangedEventArgs e)
    e.Handled = true;
    base.RaiseEvent(new RoutedEventArgs(FileNameChangedEvent));
That’s it. Build the control.

Create a WPF Application for using the Custom Control.

Step 1: In the same solution, add a new WPF Application and name it as ‘WPF40_FileUploadContainer’.

Step 2: In this project, add the reference of the ‘WPF40_FileUploadCustomControl’ library so that the control can be used.
Step 3: Open MainWindow.Xaml and register the control in XAML (Gray Marked). Use the control in XAML and subscribe the ‘FileNameChanged’ event (Green Marked) as shown below :
<Window x:Class=”WPF40_FileUploadContainer.MainWindow”
        Title=”MainWindow” Height=”481″ Width=”667″>
           <RowDefinition Height=”112*” />
            <RowDefinition Height=”330*” />
        <ccFileUpload:FileUploadCustomControl x:Name=”fileUpload”
                                              Width=”600″ Margin=”12,29,34,0″Height=”56″
        <Image Grid.Row=”1″ Height=”264″ HorizontalAlignment=”Left” Margin=”30,24,0,0″Name=”imgUploaded” Stretch=”Fill” VerticalAlignment=”Top” Width=”589″ />
Step 4: Open MainWindow.Xaml.cs and write the following code in it:
private void fileUpload_FileNameChanged(object sender, RoutedEventArgs e)
    ImageSource imgSrc = new BitmapImage(new Uri(fileUpload.FileName));
    imgUploaded.Source = imgSrc;
The above code represents the event handled on the container for the Custom Control.
Step 5: Run the application.
Once the WPF window runs, click on ‘Browse’ button and the open dialog box will be displayed. Select a ‘.jpg’ file and click on ‘Open’ button. The selected image will be displayed as shown below:
WPF Custom Control
WPF allows us to develop specialty controls using Custom Control. Before deciding to use a Custom Control, one must think about,

What functionality will be performed by the control?

This will help in selecting Visual Elements for designing UI for the control, along with the business logic for it.
What data will be either consumed by the control or published from the control?
This will help in defining dependency properties for the control. These properties will be used in DataBinding.
When will this control publish the data to its container?
This will help in defining routed event for the controls.
Categories: WPF Tags:

Bubbling and Tunneling

Let’s say you have a simple application that looks as follows:












When you hover over the Log-In button, which elements do you think receive notification of something happening?

One of the elements that gets notified is the button, as you would expect. What you may not realize is that the event propagates beyond the button and to other elements in its visual tree such as its parent, its parent’s parent, and so on.

That roundabout way of having events routed through the parents is what makes events in WPF and Silverlight known as routed events.

Let’s look at an example of a simple application broken down into its visual tree:


The application portrayed is fairly simple. It contains a Button and Label (aka TextBlock in Silverlight) control nested inside a Grid control which, in turn, is hosted by our overall Window/UserControl control. When you hover over your button, since the hover is a routed event, your MouseEnter event gets recognized by your Grid and Window/UserControl controls.

Peers are not affected. You interacting with your Button will have no affect on the Label control that is your peer. This is true even if your Label is overlapping your button. Since your Label/TextBlock is never hovered over and it is a peer of your button, it doesn’t partake in this event handling festivity!

Routing Strategies: Bubbling, Tunneling, and Direct
While I mentioned that your events get recognized by the parents, the order by which they get recognized depends on the routing strategy used. The two most popular routing strategies are bubbling and tunneling.

Bubbling Strategy
In a bubbling strategy, you start with the control that originated the event and traverse up the tree:


This is what I described earlier where the order of the elements that get notified by an event on the button goes from Button to Grid to Window. The tunneling strategy works in the opposite way.

Tunneling Strategy
With tunneling, when an event is fired, you go all the way to the root and traverse down until you hit the control that originated the event:


In WPF, you can specify which routing strategy to use based on the type of event you are listening for. If you look at the list of events your element supports, if it has the word “Preview” in front of it such as PreviewMouseLeftButtonDown, you are dealing with a tunneling event:

[ example of tunneling events ]

For most of the other events that do not have Preview in front of them, you are dealing with bubbling events.

Silverlight only supports bubbling, so you will always have events that move up to the root as opposed to starting with the root and moving down.

Tunneling and bubbling events processing sequence

The UIElement class defines many routed events for keyboard, mouse, and stylus input. Most of these are bubbling events, but many of them are paired with a tunneling event. Tunneling events can be easily identified because, by convention, they are named with a Previewprefix. These events, also by convention, are raised immediately before their bubbling counterpart. For example, PreviewMouseMove is a tunneling event raised before the MouseMove bubbling event.

Example :

The idea behind having a pair of events for various activities is to give elements a chance to effectively cancel or otherwise modify an event that’s about to occur. By convention, WPF’s built-in elements only take action in response to a bubbling event (when a bubbling and tunneling pair is defined), ensuring that the tunneling event lives up to its “”preview” name. For example, imagine you want to implement aTextBox that restricts its input to a certain pattern or regular expression (such as a phone number or zip code). If you handle TextBox‘s KeyDown event, the best you can do is remove text that has already been displayed inside the TextBox. But if you handle TextBox‘s PreviewKeyDown event instead, you can mark it as “handled” to not only stop the tunneling but also stop the bubbling KeyDown event from being raised. In this case, the TextBox will never receive the KeyDown notification and the current character will not get displayed

Where is the event for handling the pressing of a mouse’s middle button?

If you browse through the various mouse events exposed by UIElement or ContentElement, you’ll find events for MouseLeftButtonDownMouseLeftButtonUp,MouseRightButtonDown, and MouseRightButtonUp (as well as the tunneling Preview version of each event). But what about the additional buttons present on some mice?

This information can be retrieved via the more generic MouseDown and MouseUp events (which also have Preview counterparts). The arguments passed to such event handlers include a MouseButton enumeration that indicates which button’s state just changed: LeftRightMiddleXButton1, or XButton2. A corresponding MouseButtonStateenumeration indicates whether that button is Pressed or Released.

Categories: WPF Tags: ,

EventWaitHandler: AutoResetEvent vs. ManualResetEvent

Threads can communicate using WaitHandlers by signaling. Mutex, Semapore and EventWaitHandle are derived from WaitHandle class.

There are two types of EventWaitHandlers. AutoResetEvent and ManualResetEvent. AutoResetEvent lets one waiting thread at a time when Set() is called but ManualResetEvent lets all waiting threads to pass by when Set() is called. ManualResetEvent starts blocking when Reset() is called.

This acts like a turnstile which lets one at a time. When a thread hits WaitOne(), it waits till some other thread calls Set(). Take a look at the following picture. Thread1, Thread2 and Thread3 are waiting after calling WaitOne(). For every Set() call from another thread, one thread will pass the turnstile.

I have created a simple application to test this. There are two buttons to span a thread DoWork. DoWork has WaitOne call and it blocks threads. Third button calls Set() to release one thread at a time. Click first two buttons to span thread and click third button twice to release blocked threads.

private EventWaitHandle wh = new AutoResetEvent(false);
private void DoWork()
    Console.WriteLine(Thread.CurrentThread.Name + ": Waiting for Set() notification");
    // Wait for notification
    Console.WriteLine(Thread.CurrentThread.Name + ": Notified");
private void buttonCreateThreadOne_Click(object sender, EventArgs e)
    Thread a = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    a.Name = "A";
private void buttonCreateSecondThread_Click(object sender, EventArgs e)
    Thread b = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    b.Name = "B";
private void buttonReleaseOneThread_Click(object sender, EventArgs e)


Please note that the code after WaitOne call in DoWork is not thread safe. A call to Set will let next waiting thread to enter even the first thread is still executing the code.


This is like a gate which lets more than one at a time. When a thread hits WaitOne(), it waits till someother thread calls Set(). Take a look at the following picture. Thread1, Thread2 and Thread3 are waiting after calling WaitOne(). When Set is called from another thread, all waiting thereads will pass the gate.

Code snippet to illustrate the above.

private void buttonFirstThread_Click(object sender, EventArgs e)
    Thread a = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    a.Name = "A";
private void buttonSecondThread_Click(object sender, EventArgs e)
    Thread b = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    b.Name = "B";
private void buttonCallSet_Click(object sender, EventArgs e)
private void buttonCallReset_Click(object sender, EventArgs e)
Categories: C#, WPF Tags: ,

Dispatcher in WPF

February 21, 2012 2 comments

Consider the following program

   1:  <Window x:Class="DispatcherTrial.MainWindow"
   2:          xmlns=""
   3:          xmlns:x=""
   4:          Title="MainWindow" Height="350" Width="525">
   5:      <Grid>
   6:          <Grid.RowDefinitions>
   7:              <RowDefinition/>
   8:              <RowDefinition/>
   9:          </Grid.RowDefinitions>
  10:          <Button Name="MyButton" Content="Click Here" 
  11:          <TextBlock Grid.Row="1" Name="myText"></TextBlock>
  12:      </Grid>
  13:  </Window>
namespace DispatcherTrial
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

        private void MyButton_Click(object sender, RoutedEventArgs e)
            Thread myThread = new Thread(DisplayTime);

        private void DisplayTime()
            myText.Text = DateTime.Now.ToString();

The code is fairly simple. Grid having two rows, one containing button control and other having a TextBlock. In the click of event of button, I have initialized a new thread. Assigned to that thread is method called “DisplayTime”. Inside “DisplayTime” method, I am assigning the current time to the textblock control. All in all , I am trying to update the UI from code which is running on a separate thread. Ideally the code should run fine but it doesn’t. It throws an exception of type :- InvalidOperationException. And following is the error message : The calling thread cannot access this object because a different thread owns it.

I guess the error description is verbose enough to tell us what’s wrong in the above implementation. We simply cannot update the UI from a seperate thread. To understand more on this consider the following code snippet :

   1:  [STAThread]
   2:  static void Main()
   3:  {
   4:         Application app = new Application();
   5:         Window win = new Window();
   6:         win.Show();
   7:         app.Run();
   8:  }

The main method here is tagged with “STAThread” attribute. STA stands for “Single Threaded Apartment” model of programming. What STA states(or enforces) is that only one thread at a time will be executing our code and it will always be the same thread. All our Winform based application runs on STA model. Indeed one thread controlling the complete application looks like a big constraint and WPF people actually decided to move away from this model by opting an all together different approach. But the plan was abandoned because of various compatibility issues with other already existing applications. So our WPF applications too run on STA model. The thread the controls the application is commonly known as UIThread. “Dispatcher” concept is a mechanism introduced in WPF , with the help of which developer can have more explicit control on this UI thread as of what executes when. We will look into this in more details in the remaining section of this article. But before we take a deep dive, just try to keep in mind the below mentioned points about STA model.

  • Thread that creates a given WPF application also own it and its not possible for any other thread to interact with these elements.
  • In practice entire WPF application runs of single thread and its this thread that owns all the elements in the application.

Dispatcher Concept

As the name implies, the dispatching system is responsible for listening to various kinds of messages and making sure that any object that needs to be notified of that message is notified on the UI thread.

The classes responsible for “Dispatcher” concept are : DispatcherObject and Dispatcher. Actually its the “Dispatcher” class which provides the core implementation of dispatching mechanism. But its the “DispatcherObject” class which exposes a public property called “Dispatcher” , through which we can access the current instance of “Dispatcher” class. Have a look at the following class hierarchy diagram :


From the above picture its evident that almost every single entity in WPF derives from the “DispatcherObject” class. Following is the internal implementation of “DispatcherObject” class.

   1:  public abstract class DispatcherObject
   2:  {
   3:      // Fields
   4:      private Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
   6:      // Methods
   7:      protected DispatcherObject()
   8:      {
   9:      }
  11:       public bool CheckAccess()
  12:      {
  13:          bool flag = true;
  14:          Dispatcher dispatcher = this._dispatcher;
  15:          if (dispatcher != null)
  16:          {
  17:              flag = dispatcher.CheckAccess();
  18:          }
  19:          return flag;
  20:      }
  22:      internal void DetachFromDispatcher()
  23:      {
  24:          this._dispatcher = null;
  25:      }
  27:       public void VerifyAccess()
  28:      {
  29:          Dispatcher dispatcher = this._dispatcher;
  30:          if (dispatcher != null)
  31:          {
  32:              dispatcher.VerifyAccess();
  33:          }
  34:      }
  36:      // Properties
  38:      public Dispatcher Dispatcher
  39:      {
  40:          get
  41:          {
  42:              return this._dispatcher;
  43:          }
  44:      }
  45:  }

“DispatcherObject” class offers a public accessor property called “Dispatcher” using which we can access the current instance of “Dispatcher” class. Speaking about “Dispatcher” class, it is responsible for managing the work that takes place in our WPF application.Its this class which owns the application thread and internally it maintains a queue of work items. As the WPF application runs , Dispatcher class accepts incoming requests and executes them one at a time. In short dispatcher is an object which receives messages and delivers it to the correct object for further processing. Dispatcher class is pretty dense with lots of properties and methods. Going into the depth of Dispatcher class is beyond the scope of this article. One final thing on dispatcher class is that a given application can have only one instance of dispatcher class( as the application runs on single thread) , so Dispatcher class implements the very famous “Singleton” pattern. Because of that its impossible to create an instance of Dispatcher class in our custom code. Only with the help of public property “Dispatcher” offered by “DispatcherObject” that we can invoke members defined inside the “Dispatcher” class. Dispatcher class is instantiated as soon as any class which derives from “DispatcherObject” is accessed. All further request are processed by this newly created instance.

Coming back to “DispatcherObject” class , it offers two methods namely CheckAccess and VerifyAccess.

  • CheckAccess : Determines whether the calling thread has access to this DispatcherObject. Only possible return values are true and false.
  • VerifyAccess : VerifyAccess is more stringent compared to CheckAccess. It checks whether the calling thread is the one which created the DispatcherObject. If not it throws “InvalidOperationAccess” exception. Getting back to the example which I gave in the beginning, in that we were trying to update the UI through code which was running on a different thread. Internally VerifyAcess is invoked and once it verifies that calling code is different from the one which controls the application, it throws the “InvalidOperationError” exception.


I have spoken so much on the classes which enable dispatching scenario in WPF. But at the end of the day WPF works on STA model. So how does this whole “Dispatcher” stuff going to help us ? As mentioned before , Dispatcher maintains an internal queue of work items and it process each work items one after the other. Each work item in the queue is has its associated priority. Items are executed relatively to each other on the basis of their priority values. Items with high priority value will be executed before any other items with low priority values. Possible values for the priority field is represented by an enum called “DispatcherPriority”.

   1:  public enum DispatcherPriority
   2:  {
   3:      ApplicationIdle = 2,
   4:      Background = 4,
   5:      ContextIdle = 3,
   6:      DataBind = 8,
   7:      Inactive = 0,
   8:      Input = 5,
   9:      Invalid = -1,
  10:      Loaded = 6,
  11:      Normal = 9,
  12:      Render = 7,
  13:      Send = 10,
  14:      SystemIdle = 1
  15:  }

Now as a WPF programmer, we can push our custom time consuming logic into the queue maintained by the “Dispatcher” class and associate a lower priority value to that work item. Based on the value of priority field the corresponding code will be executed at the specified interval. Important thing to note here is that all the work is still being done by the UIthread, its just that with the help of DispatcherPriority we have prioritized our tasks. Ideally its recommended to give priority values less then 7(render) to the custom logic that we wish to execute with the help of Dispatcher. Most often priority value “Background” is used for application specific custom logic. MS Word spell check is implemented with the help of this mechanism and priority value is “ApplicationIdeal”. Following is the modified code for the example which I have provided in the beginning of the article:

   1:  namespace DispatcherTrial
   2:  {
   3:      /// <summary>
   4:      /// Interaction logic for MainWindow.xaml
   5:      /// </summary>
   6:      public partial class MainWindow : Window
   7:      {
   8:          public MainWindow()
   9:          {
  10:              InitializeComponent();
  11:          }
  13:          private void MyButton_Click(object sender, RoutedEventArgs e)
  14:          {
  15:              this.Dispatcher.BeginInvoke(new Action(this.DisplayTime)
                                           , DispatcherPriority.Background);
  16:          }
  18:          private void DisplayTime()
  19:          {
  20:              myText.Text = DateTime.Now.ToString();
  21:          }
  22:      }
  23:  }

”BeginInvoke” is a member exposed by the “Dispatcher” class. BeginInvoke adds the delegate to the Dispatcher’s event queue but gives you the opportunity to specify a lower priority for it. This ensures that the Dispatcher processes all loading and rendering events
before executing the delegate that loads the data. This allows the control or window to be displayed and rendered immediately, whilst the data waits in the background to be loaded.


Proper use of threads can greatly increase the responsiveness of your WPF applications. Unfortunately, you can’t update any UI controls from a thread that doesn’t own the control. In .NET 2.0, you used Control.Invoke(). Now, we’ve got something similar but more powerful – the Dispatcher. This tutorial will explain what the Dispatcher is and how to use it.

First of all, you need to know where the Dispatcher lives. Every Visual (Button, Textbox, Combobox, etc.) inherits from DispacterObject. This object is what allows you to get a hold of the UI thread’s Dispatcher.

The Dispatcher is why you can’t directly update controls from outside threads. Anytime you update a Visual, the work is sent through the Dispatcher to the UI thread. The control itself can only be touched by it’s owning thread. If you try to do anything with a control from another thread, you’ll get a runtime exception. Here’s an example that demonstrates this:

public partial class Window1 : Window
public Window1()

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
myCheckBox.IsChecked = true;

This code creates a Checkbox, then creates a thread which tries to change the checked state. This will fail because the Checkbox was created on a different thread than the one trying to modify it. If you run this code, you’ll end up with this exception:

The calling thread cannot access this object because a different thread owns it.
So the question is, how do you update the Checkbox from this thread? Fortunately, the Dispatcher gives us the ability to Invoke onto its thread. Invoking probably looks really familiar if you’ve programmed in .NET 2.0. We actually have an in-depth tutorial on invoking that you might want to read. Below is code using the Dispatcher that will run and update the Checkbox without throwing an exception.

public Window1()

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
new Action(
myCheckBox.IsChecked = true;

Now we’ve introduced the Dispatcher object. The call to Invoke needs to take a few pieces of information. First is the priority you’d like your work executed with. Next is the delegate that contains the work you actually want to do. If your delegate takes parameters, the Invoke call will also accept an Object or Object[] to pass into the delegate function. It will also accept a timespan that limits the amount of time the Invoke call will wait to execute your code.

The call to Invoke will block until your function has been executed. Depending on the priority you’ve set, this might take a while. The Dispatcher also has the ability to invoke code asynchronously using BeginInvoke. Let’s look at the same example using BeginInvoke.

public Window1()

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
dispatcherOp = myCheckBox.Dispatcher.BeginInvoke(
new Action(
myCheckBox.IsChecked = true;

dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);


void dispatcherOp_Completed(object sender, EventArgs e)
Console.WriteLine(“The checkbox has finished being updated!”);
BeginInvoke takes many of the same arguments as Invoke, but now returns a DispatcherOperation that lets you keep track of the progress of your function. In this case, I simply hooked the Completed event that notifies me when the work has been completed. The DispatcherOperation object also lets you control the Dispatcher by changing its priority or aborting it all together.

As I mentioned above, we can limit the amount of time an Invoke is allowed to take my passing the Invoke call a TimeSpan structure. Here’s an example that will wait 1 second for the queued function to complete:

public Window1()

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
new Action(
myCheckBox.IsChecked = true;

Unfortunately, there’s no way to determine if the invoke finished or timed out from the outside. You can always put code inside the invoked function to determine if it executed.

All right, so we’ve got our dispatchers working and code is being executed where it’s supposed to be. Invokes, however, are kind of an expensive process. What happens when your controls are being updated from both external threads and the main UI thread. How do you know if you’re supposed to use Invoke? The Dispatcher object provides a function that tells you whether or not you have to use Invoke. In WinForms you call InvokeRequired on the actual control. In WPF, you call CheckAccess() on the Dispatcher object. CheckAccess() returns a boolean indicating whether or not you can modify the control without Invoking.

if (!myCheckBox.Dispatcher.CheckAccess())
new Action(
myCheckBox.IsChecked = true;
myCheckBox.IsChecked = true;
So now, before I invoke, I check to see if I even need to. If I do, I invoke the function, if I don’t, I simply update the control directly.

As you can see, the Dispatcher provides a great deal of flexibility over the WinForms Invoke. There’s a lot about WPF’s dispatching model that we didn’t touch in this tutorial. The System.Windows.Threading namespace contains a lot more useful objects that extends the power of the dispatcher even further. If you’ve got questions or have found crazy uses for the Dispatcher, leave them in the comments.

Categories: WPF Tags:

UI Thread, Dispatchers, Background Workers & Async Network Programming

February 5, 2012 1 comment

Both Silverlight and WPF have the concept of a UI thread. Whenever you tie that thread up, you make your application unresponsive. In Silverlight, if you’re on a page with other plug-ins, you make all the plug-ins unresponsive. (It’s actually per-process, but most modern browsers separate processes by tabs)

Async Network Calls

In order to keep from tying up the UI thread, you have to perform long-running processes on another thread. Often, but not always, those processes are network calls. In Silverlight, all network calls are async with no provision to handle them any other way. This lets you off the hook threading-wise, but requires that you understand how to chain those calls, and how to deal with libraries that have IAsyncResult callbacks that return on different threads.
TestServiceClient client = new TestServiceClient();

client.DoSomethingSlowCompleted+= (s, ea) =>{

     // do something with the results here

Background Worker

For other processes, the BackgroundWorker is a great, simple, way to do some background work while reporting progress to the UI. It takes all the dispatching work away, so you can feel free to manipulate the UI from the ProgressChanged and RunWorkerCompleted events. Do not touch the UI from the DoWork event, as that is actually running on a separate thread.

private BackgroundWorker _worker = new BackgroundWorker();

private void RunLongProcess() {    

     _worker.WorkerReportsProgress = true;

     ProgressBar.Minimum = 0;

     ProgressBar.Maximum = 100;

    // runs in Background Thread
     _worker.DoWork += (s, e) =>
           for (int i = 0; i < 100; i++)
                 // simulate long-running work

 // runs in UI Thread

     _worker.ProgressChanged += (s, e) => {
            // this is on the UI thread, so you can update UI from here.
            ProgressBar.Value = e.ProgressPercentage;

   // runs in UI Thread

     _worker.RunWorkerCompleted += (s, e) => {
            // clean up after your stuff, yes, you can touch UI here.

Of course, knowing how to set up event handlers using lambda expressions is always helpful 🙂


Sometimes, you spin off a thread of your own, or you have to deal with some of the crufty stacks where the callbacks come back on a different thread from the one that created the call. In those cases, you need to use a dispatcher to make a call back to the UI thread.

If the code is on a page, you can call the dispatcher property and pass it a function to execute (yes, more lambda in this example).

private void UpdateUI(){Dispatcher.BeginInvoke(() =>{ProgressBar.Value = 50;});}

But, if the code is in some sort of non-UI class, it gets more complex. You can do it this way, using a dummy control (like we did in Silverlight 2):

TextBlock _dispatcherObject = new TextBlock();private void UpdateUINasty() // avoid this approach unless it’s all you’ve got{_dispatcherObject.Dispatcher.BeginInvoke(() =>{SomePage.ProgressBar.Value = 50; });}

This example assumes the object itself was created on the UI thread. The better way is to use the Deployment object:

private void UpdateUINotSoNasty(){Deployment.Current.Dispatcher.BeginInvoke(() =>{SomePage.ProgressBar.Value = 50;});}

That’s better. Definitely the recommended approach for recent versions of Silverlight, including Windows Phone 7.


What about when you need to run something on a timer? The normal timer classes require manual dispatching to do any UI updates. However, Silverlight and WPF both have the DispatcherTimerclass that handles all that for you.

private void StartTimer(){DispatcherTimer timer = new DispatcherTimer();timer.Tick += (s, e) =>{
// do some very quick work here update the UI

StatusText.Text = DateTime.Now.Second.ToString();

timer.Interval = TimeSpan.FromSeconds(1);

Of course, realize that what you’re doing here is interrupting the UI thread, not really running anything on a separate thread. It’s not suitable for anything long-running and cpu-intensive, but rather something where you need to execute on a regular interval. Clock UI updates are a perfect example.


In general, I discourage folks from spinning off real threads. Very few people understand how to efficiently work with threads, so even if you’re a threading genius, the person coming in after you probably isn’t. In most cases, the Background Worker will provide you with what you need.

Silverlight doesn’t yet have it, but the Parallel Tasking support built into .NET 4 can really help you out should you really need to do more than two things at once. Definitely check it out.


Threading in Silverlight and WPF is a little trickier than some other technologies, because you have to worry about the UI thread. My intention here was to both inform you that this trickiness exists, and then show some ways of dealing with it.


The goal of this article is to clearly explain the differences between these 3 architectures.

Common Elements

First, the let’s define common elements.  All 3 of the architectures are designed to separate the view from the model.


  • Domain entities & functionality
  • Knows only about itself and not about views, controllers, etc.
  • For some projects, it is simply a database and a simple DAO
  • For some projects, it could be a database/file system, a set of entities, and a number of classes/libraries that provide additional logic to the entities (such as performing calculations, managing state, etc)

Implementation: Create classes that describe your domain and handle functionality.  You probably should end up with a set of  domain objects and a set of classes that manipulate those objects.


  • Code that handles the display
  • Note that view related code in the codebehind is allowed (see final notes at the bottom for details)

Implementation:  HTML, WPF, WindowsForms, views created programmatically – basically code that deals with display only.

Differences between Presenters, ViewModels and Controllers

This is the tricky part.  Some things that Controllers, Presenters, and ViewModels have in common are:

  • Thin layers
  • They communicate with the model and the view

The features of each.

Presenter (Example: WinForms)

  • 2 way communication with the view
  • View Communication: The view communicates with the presenter by directly calling functions on an instance of the presenter.  The presenter communicates with the view by talking to an interface implemented by the view.
  • There is a single presenter for each view


  • Every view’s codebehind implements some sort of IView interface.  This interface has functions like displayErrorMessage(message:String), showCustomers(customers:IList<Customer>), etc.  When a function like showCustomers is called in the view, the appropriate items passed are added to the display.  The presenter corresponding to the view has a reference to this interface which is passed via the constructor.
  • In the view’s codebehind, an instance of the presenter is referenced.  It may be instantiated in the code behind or somewhere else.  Events are forwarded to the presenter  through the codebehind.  The view never passes view related code (such as controls, control event objects, etc) to the presenter.

ViewModel (Example: WPF)

  • 2 way communication with the view
  • The ViewModel represents the view.  This means that fields in a view model usually match up more closely with the view than with the model.
  • View Communication:  There is no IView reference in the ViewModel.  Instead, the view binds directly to the ViewModel.  Because of the binding, changes in the view are automatically reflected in the ViewModel and changes in the ViewModel are automatically reflected in the view.
  • There is a single ViewModel for each view


  • The view’s datacontext is set to the ViewModel.  The controls in the view are bound to various members of the ViewModel.
  • Exposed ViewModel proproperties implement some sort of observable interface that can be used to automatically update the view (With WPF this is INotifyPropertyChanged; with knockoutjs this is done with the functions ko.observable() and ko.observrableCollection())

Controller (Example: ASP.NET MVC Website)

  • The controller determines which view is displayed
  • Events in the view trigger actions that the controller can use to modify the model or choose the next view.
  • There could be multiple views for each controller
  • View Communication:
    • The controller has a method that determines which view gets displayed
    • The view sends input events to the controller via a callback or registered handler.  In the case of a website, the view sends events to the controller via a url that gets routed to the appropriate controller and controller method.
    • The view receives updates directly from the model without having to go through the controller.
      • Note: In practice, I don’t think this particular feature of MVC is employed as often today as it was in the past.  Today, I think developers are opting for MVVM (or MVP) over MVC in most situations where this feature of MVC would have been used.  Websites are a situation where I think MVC is still a very practical solution.  However, the view is always disconnected from the server model and can only receive updates with a request that gets routed through the controller.  The view is not able to receive updates directly from the model.

Implementation (for web):

  • A class is required to interpret incoming requests and direct them to the appropriate controller.  This can be done by just parsing the url. MVC does it for you.
  • If required, the controller updates the model based on the request.
  • If required, the controller chooses the next view based on the request.  This means the controller needs to have access to some class that can be used to display the appropriate view. MVC provides a function to do this that is available in all controllers.  You just need to pass the appropriate view name and data model.


MVVM and MVP implementation seem pretty straightforward but MVC can be a little confusing.  The diagram below from Microsoft’s Smart Client Factory documentation does a great job at showing MVC communication.  Note that the controller chooses the view (ASP.NET MVC) which is not shown in this diagram.  MVVM interactions will look identical to MVP (replace Presenter with ViewModel).  The difference is that with MVP, those interactions are handled programmatically while with MVVM, they will be handled automatically by the data bindings.


 General rules for when to use which?


  • Use in situations where binding via a datacontext is not possible.
  • Windows Forms is a perfect example of this.  In order to separate the view from the model, a presenter is needed.  Since the view cannot directly bind to the presenter, information must be passed to it view an interface (IView).


  • Use in situations where binding via a datacontext is possible.  Why?  The various IView interfaces for each view are removed which means less code to maintain.
  • Some examples where MVVM is possible include WPF and javascript projects using Knockout.


  • Use in situations where the connection between the view and the rest of the program is not always available (and you can’t effectively employ MVVM or MVP).
  • This clearly describes the situation where a web API is separated from the data sent to the client browsers.  Microsoft’s ASP.NET MVC is a great tool for managing such situations and provides a very clear MVC framework.

Final notes

  • Don’t get stuck on semantics.  Many times, one of your systems will not be purely MVP or MVVM or MVC.  Don’t worry about it.  Your goal is not to make an MVP, MVVM, or MVC system.  Your goal is to separate the view, the model, and the logic that governs both of them. It doesn’t matter if your view binds to your ‘Presenter’, or if you have a pure Presenter mixed in with a bunch of ViewModels.  The goal of a maintainable project is still achieved.
  • Some evangelists will say that your ViewModels (and Presenters) must not make your model entities directly available for binding to the view.   There are definitely situations where this is a bad thing.  However, don’t avoid this for the sake of avoiding it.  Otherwise, you will have to constantly be copying data between your model and ViewModel.  Usually this is a pointless waste of time that results in much more code to maintain.
  • In line with the last point, if using WPF it makes sense to implement INotifyPropertyChanged in your model entities.  Yes, this does break POCO but when considering that INotifyPropertyChanged adds a lot of functionality with very little maintenance overhead , it is an easy decision to make.
  • Don’t worry about “bending the rules” a bit so long as the main goal of a maintainable program is achieved
  • Views
    • When there is markup available for creating views (Xaml, HTML, etc), some evangelists may try to convince developers that views must be written entirely in markup with no code behind.  However, there are perfectly acceptable reasons to use the code behind in a view if it is dealing with view related logic.  In fact, it is the ideal way to keep view code out of your controllers, view models, and  presenters.  Examples of situations where you might use the code behind include:
      • Formatting a display field
      • Showing only certain details depending on state
      • Managing view animations
    • Examples of code that should not be in the view
      • Sending an entity to the database to be saved
      • Business logic
Categories: C#, WPF Tags: , ,
%d bloggers like this: