Guilherme Guilherme -4 years ago 228
C# Question

Write on textbox in a thread (TASK) in WPF Application

I have a program (In WPF Application) which receive by a thread info from COM port.
Here's part from that:

static async Task ReceiveData(SerialPort port)
{
try
{
Thread.Sleep(50); // Time for read works
await port.BaseStream.ReadAsync(buffer, 0, 55); //Wait recive data from Serial Port

textBox.AppendText("Test");
}
}


The problem occurs because it can be write in the text box just in this task.
I have a lot of others textBox outside and works just fine.
The error who show is:


An object reference is required for the non-static field, method, or
property 'MainWindow.textBox'


If I change the task for public the error disappears but when I build the program the text don't appear on the box.

I know the message it's about reference but it seems this part is OK, I think it's something about turn the textBox in public access.

I change the code just for:

async Task ReceiveData(SerialPort port)


And the following error appears on output:


Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll


And the error is: ""The calling thread cannot access this object because a different thread owns it.""

---------- SOLVED BY @BrandonKramer ----------
Using:

Dispatcher.BeginInvoke((Action)(() => textBox.AppendText("Test")));

Answer Source

Your error is because UI elements, such as a TextBox, can only be modified from the UI thread.

In order to fix this issue, change:

textBox.AppendText("Test");

to

Dispatcher.BeginInvoke((Action)(() => textBox.AppendText("Test")));

This will cause textBox.AppendText("Test"); to be executed on the UI thread, rather then the background thread that your task is executing on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download