Updating XAML controls from a button press throws a WRONG THREAD error

Hi All;

I’m working on a UI project, and if I update the controls on my screen using a button on the screen, or a timer, it works fine, but the same function, when called from a button press, throws an RPC_E_WRONG_THREAD error:

txtMoisture.Text = Math.Floor(reading).ToString() + "%";
txtStatus.Text = StatusMessage;

Those two lines are the guilty party, but how do I get them into the UI thread?

Usually it is done through Dispatcher:

if (!Dispatcher.CheckAccess())

That gives me somewhere to start googling, thanks!

I think you need to use BeginInvoke()

  private delegate void SetLabelTextDelegate(int number);
   private void SetLabelText(int number)
      // label.Text = number.ToString();
      // Do NOT do this, as we are on a different thread.

      // Check if we need to call BeginInvoke.
      if (this.InvokeRequired)
         // Pass the same function to BeginInvoke,
         // but the call would come on the correct
         // thread and InvokeRequired will be false.
         this.BeginInvoke(new SetLabelTextDelegate(SetLabelText), 
                                          new object[] {number});

      label.Text = number.ToString();

What I found here seems to be working:

var IGNORE_ME = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                txtMoisture.Text = Math.Floor(reading).ToString() + "%";
                txtStatus.Text = StatusMessage;

I should have refreshed before posting, lol

@ mtylerjr - NP, glad for the help.

You don’t need the “var IGNORE_ME =”, so you can just remove that.

Also, I recommend checking access unless you’re positive this code will only be called from a place that requires dispatching. This runs asynchronously and does take a bit more time than a regular call.


Thanks Pete, I started without it, but when it put green underlines around the code for not catching the return I felt compelled to obey VS.