0

Hi I am trying to update a label in my WPF GUI from another class, which is not the GUI with this code:

 System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(new Action(() => 
     {
         ((MainWindow)System.Windows.Application.Current.MainWindow)
             .lblError.Content = exception.Message; 
     }));

Sometimes however I get the following exception and the update does not work:

Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll (" The calling thread can not access this object because the object is owned by another thread .")

Why does my delegate not work? Is there an easy way to do what I want to do (update a label of my GUI from another class) without too much effort?

Emond
  • 50,210
  • 11
  • 84
  • 115
DerBenutzer
  • 311
  • 1
  • 5
  • 20

1 Answers1

2

The error message tells you exactly what is wrong: you need to use the dispatcher of the UI element you are updating.

This is not dependent on the class, it is dependent on the current thread.

To access the correct thread use the Dispatcher property of the the element you are trying to update:

lblError.Dispatcher.Invoke(new Action(() ...

See also How to update the GUI from another thread in C#?

Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115
  • This does not work and still gives me the same error. This is how I tried to implement your proposal: ((MainWindow)System.Windows.Application.Current.MainWindow).lblError.Dispatcher.Invoke(new Action(() => { ((MainWindow)System.Windows.Application.Current.MainWindow).lblError.Content = exception.Message; })); – DerBenutzer Feb 15 '16 at 15:57
  • Make sure you use the dispatcher of the label. If that fails log the name of the thread that executes the label modifying code. – Emond Feb 15 '16 at 16:36