UI and threads with WPF

  • .NET

Proper use of threads avoids blocking windows. However this requires some precoctions. The problem is quite simple, just run this example and see the error generated.

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 to solve this error?

The problem is that actions are not executed on the same thread as the one controls where created. So you need to find a way to perform the UI modification actions on the correct thread.

To do this, you must use the Dispatcher. It has a method Invoke and a method BeginInvoke. These are the methods that will allow us to perform actions on the thread of the control. Indeed you will be able to pass a delegate and parameters (to use the delegate)

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 on Twitter or by email!

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal