Prevent UI from freezing without additional threads

If you only use a single thread then the UI will freeze while you do any amount of processing.

If you use a BackgroundWorker thread you'll have more control over what happens & when.

To update the UI you need to use Dispatcher.Invoke from your background thread to marshal the call across the thread boundary.

Dispatcher.Invoke(DispatcherPriority.Background,
                  new Action(() => this.TextBlock.Text = "Processing");

Here is a wonderful blog posting from Dwane Need that discusses all the available options for working with UI elements amongst multiple threads.

You really haven't given enough detail to give a good prescription. For example, why are you creating UI elements yourself at all instead of using databinding? You might have a good reason, but without more details it's hard to give good advice. As another example of detail that would be useful, are you looking to build complex deeply nested control hierarchies for each piece of data or do you just need to draw a simple shape?


You can turn the flow of control on its head using DispatcherFrames, allowing a deserialization to proceed on the UI thread in the background.

First you need a way to get control periodically during deserialization. No matter what deserializer you are using, it will have to call property sets on your objects, so you can usually add code to the property setters. Alternatively you could modify the deserializer. In any case, make sure your code is called frequently enough

Each time you receive control, all you need to do is:

  1. Create a DispatcherFrame
  2. Queue an event to the dispatcher using BeginInvoke that sets Continue=false on the frame
  3. Use PushFrame to start the frame running on the Dispatcher

In addition, when calling the deserializer itself make sure you do it from Dispatcher.BeginInvoke, or that your calling code doesn't hold any locks etc.

Here's how it would look:

  public partial class MyWindow
  {
    SomeDeserializer _deserializer = new SomeDeserializer();

    byte[] _sourceData;
    object _deserializedObject;

    ...

    void LoadButton_Click(...)
    {
      Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
      {
        _deserializedObject = _deserializer.DeserializeObject(_sourceData);
      }));
    }
  }

  public class OneOfTheObjectsBeingDeserializedFrequently
  {
    ...

    public string SomePropertyThatIsFrequentlySet
    {
      get { ... }
      set { ...; BackgroundThreadingSolution.DoEvents(); }
    }
  }

  public class BackgroundThreadingSolution
  {
    [ThreadLocal]
    static DateTime _nextDispatchTime;

    public static void DoEvents()
    {
      // Limit dispatcher queue running to once every 200ms
      var now = DateTime.Now;
      if(now < _nextDispatchTime) return;
      _nextDispatchTime = now.AddMilliseconds(200);

      // Run the dispatcher for everything over background priority
      var frame = new DispatcherFrame();
      Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
      {
        frame.Continue = false;
      }));
      Dispatcher.PushFrame(frame);
    }
  }

Checking DateTime.Now in DoEvents() isn't actually required for this technique to work, but will improve performance if SomeProperty is set very frequently during deserialization.

Edit: Right after I wrote this I realized there is an easier way to implement the DoEvents method. Instead of using DispatcherFrame, simply use Dispatcher.Invoke with an empty action:

    public static void DoEvents()
    {
      // Limit dispatcher queue running to once every 200ms
      var now = DateTime.Now;
      if(now < _nextDispatchTime) return;
      _nextDispatchTime = now.AddMilliseconds(200);

      // Run the dispatcher for everything over background priority
      Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new Action(() => {}));
    }