0

I'm trying to update my WPF GUI from another thread. I've found some solutions with using the Dispatcher but it's still not working.

For example I'm using it in a catch block:

catch (Exception err){
    Dispatcher.BeginInvoke((Action)(() => {
        pConsole.AppendText(err.Message);
        pConsole.ScrollToEnd();
    }));
    return;
}

pConsole is a RickTextBox.

With the dispatcher there is an output at the pConsole, but the output is:

The calling thread cannot access this object because a different thread owns it.

Any idea what's wrong?

7
  • do you try to use pConsole.Dispatcher (see example here) ? Commented Jan 28, 2020 at 11:10
  • 1
    Try Application.Current.Dispatcher. Commented Jan 28, 2020 at 11:10
  • Did you try this.Dispatcher.Invoke(() => { pConsole.AppendText(err.Message); pConsole.ScrollToEnd(); }); Commented Jan 28, 2020 at 11:32
  • Thx for your replys @PrajeeshTS @vasily.sib @Clemens. I've now tried with pConsole.Dispatcher and Application.Current.Dispatcher and this.Dispatcher.Invoke(() => { pConsole.AppendText(err.Message); pConsole.ScrollToEnd(); }); . Unfortunately it's the same result on all of them. Commented Jan 28, 2020 at 11:42
  • Can you also try Dispatcher.BeginInvoke( new ThreadStart(() => pConsole.AppendText(err.Message); pConsole.ScrollToEnd();); Commented Jan 28, 2020 at 12:10

2 Answers 2

1

It doesn't look like there is a problem with the code you have posted, but since you write that the RichTextBox actually receives the text

The calling thread cannot access this object because a different thread owns it.

it seems like your exception handling code is working as it should, but catching an exception coming from the code in your try block.

In other words, check that the cause of the InvalidOperationException isn't in the try block.

Sign up to request clarification or add additional context in comments.

Comments

0

For a change, try appending the stack trace and the message to your RTF box.

catch (Exception err){
    Dispatcher.BeginInvoke((Action)(() => {
        pConsole.AppendText(err.Message);
        pConsole.AppendText(err.StackTrace);
        pConsole.ScrollToEnd();
    }));
    return;
}

There is nothing wrong with the code you wrote, it is just displaying the error message which was generated in the try block itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.