UI and threads with WPF

 
 
  • Gérald Barré

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

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 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)

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?Buy Me A Coffee💖 Sponsor on GitHub