user492536
user492536

Reputation: 907

C# Problem setting Label Content in WPF App From Separate Thread

I have a window that contains a label (player1). I also have a class that gathers data asynchronously in the background inside a thread. When that data has been gathered, I want to changed the content of my label. Since the label was created by the UI and I'm trying to edit it from another thread, I tried using Dispatcher. However, after hours of trying and different examples, I can't get it to work. In it's most simple form below, the method dispatchP1 changes the value of player1 when called from my main window. However, it doesn't work when called from my class. Also, I don't receive an error or anything.

public delegate void MyDelegate();

public void dispatchP1()
 {
 player1.Dispatcher.BeginInvoke(new MyDelegate(p1SetContent));
 }

public void p1SetContent()
 {
 player1.Content = "text";
 }

Any help would be appreciated.

Upvotes: 2

Views: 3337

Answers (2)

Erik Noren
Erik Noren

Reputation: 4339

You know you can use anonymous delegates?

player1.Dispatcher.BeginInvoke( () =>
{
   player1.Content = "text";
});

Upvotes: 1

vcsjones
vcsjones

Reputation: 141638

That code doesn't seem particularly problematic - but WPF has a habit of swallowing exceptions. In your App.xaml, you can handle the event DispatcherUnhandledException and put a breakpoint in there to determine if it is really throwing an exception or not.

Upvotes: 1

Related Questions