Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading Errors in C#

I am trying to update a text box. I thought my threading code would fix the problem, but it does not. Can anyone help with this?

new Thread((ThreadStart)delegate { txtCapacitance.Text = Math.Round(capacitance, 3).ToString(); }).Start();

Gives the following error:

Cross-thread operation not valid: Control 'txtCapacitance' accessed from a thread other than the thread it was created on.

Note that all this is being started by a dataReceived function which is called whenever USB data is received.

like image 801
Adam Avatar asked Apr 08 '10 04:04

Adam


2 Answers

UI objects can only be called from the UI thread. This can be accomplished via the Control's Invoke method:

txtCapacitance.Invoke((Action)(() => { txtCapacitance.Text = Math.Round(capacitance, 3).ToString(); }));
like image 147
Marcelo Cantos Avatar answered Sep 20 '22 23:09

Marcelo Cantos


You should rather have a look at using BackgroundWorker Class

Have a look at

C# BackgroundWorker Tutorial.

like image 20
Adriaan Stander Avatar answered Sep 18 '22 23:09

Adriaan Stander