Calling a function from another thread in C #

I have a main GUI thread with the XYZ () function to do something with a graphical interface. In another thread, if I call XYZ () from the handle of the main GUI, it displays an error: "Cross-thread operation does not work:" Control Button00 β€œaccess from a thread other than the thread it was created."

How do i solve this? I think I need to send a message to the GUI thread to execute the XYZ function. Please help me.

Thanks.

Ankata p>

+4
source share
2 answers

The reason you get this error message is because you are trying to update the GUI control from a thread other than the main one, which is not possible. GUI controls should always be changed in the same thread that was used to create them.

You can use Invoke if InvokeRequired , which will march the call to the main thread. Here is a good article .

But probably the easiest solution would be to simply use BackgroundWorker , since you no longer need to manually route calls to the User Interface. This is done automatically:

var worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { // call the XYZ function e.Result = XYZ(); }; worker.RunWorkerCompleted += (sender, e) => { // use the result of the XYZ function: var result = e.Result; // Here you can safely manipulate the GUI controls }; worker.RunWorkerAsync(); 
+7
source

In the general graphical interface in C #, only the same stream can be updated that was created if it is not the same stream as the InvokeRequired value, then true, otherwise it is false, if it is true, you call the same method again, but from GUI created on the same thread

you should use it as follows:

  delegate void valueDelegate(string value); private void SetValue(string value) { if (someControl.InvokeRequired) { someControl.Invoke(new valueDelegate(SetValue),value); } else { someControl.Text = value; } } 

Try this for more info.

How to update GUI from another thread in C #?

+3
source

All Articles