UI and threads with WPF

 
 
  • Gérald Barré

Using threads properly prevents the UI from freezing, but it requires some care. Run the following example to see the error it generates.

C#
public MainWindow()
{
    InitializeComponent();
    TextBox textBox1 = new TextBox();
    Thread t = new Thread(() => textBox1.Text = "foobar");
    t.Start();
}

This code generates the following error:

The calling thread cannot access this object because a different thread owns it.

How do you fix this error?

The problem is that the action is not executed on the same thread on which the controls were created. You need a way to perform UI updates on the correct thread.

To do this, use the Dispatcher, which provides the Invoke and BeginInvoke methods. These methods let you execute a delegate on the control's owning thread, along with any parameters it needs.

C#
public MainWindow()
{
    InitializeComponent();
    TextBox textBox1 = new TextBox();
    textBox1.Dispatcher.BeginInvoke(
        System.Windows.Threading.DispatcherPriority.Normal,
        new DispatcherOperationCallback(arg =>
             {
                 textBox1.Text = "foobar";
                 return null;
             }), null);
}

And now, it works.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?