xKushGene
xKushGene

Reputation: 21

WPF Invoke and MethodInvoker

I have an error in my application where the program crashes because of multiple threads of one object. Because I am new in C# and already learning it. I am not much familar with the Invokes etc.

Here is the Code which is the reason for my crash:

private void AppendText(string text)
{
    this.Invoke(new MethodInvoker(delegate
    {
        this.richTextBox.AppendText(text + Environment.NewLine);
    }));
}

UpdateProcess.OutputDataReceived += (s, e) => richTextBox.AppendText(e.Data);

But WPF doesn't know of this (I never worked with Invoke in WPF before so I don't know how to write it in WPF maybe u can link me to a website?)

Upvotes: 0

Views: 1023

Answers (1)

opewix
opewix

Reputation: 5083

In WPF there is Dispatcher class, which will allow you to update UI from non-UI threads:

private void AppendText(string text)
{        
    Dispatcher.BeginInvoke(() =>
    {
        this.richTextBox.AppendText(text + Environment.NewLine);
    });
}

Upvotes: 2

Related Questions