Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function from other thread in C#

Tags:

c#

I have main GUI thread with a function XYZ() to do something about GUI. In other thread, if I call XYZ() from handle of main GUI, it display error "Cross-thread operation not valid: Control 'Button00' accessed from a thread other than the thread it was created on."

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

Thanks.

Ankata

like image 438
Ankata Avatar asked Dec 29 '22 04:12

Ankata


2 Answers

The reason you are getting this error message is because you are trying to update a GUI control from a different thread than the main which is not possible. GUI controls should always be modified on the same thread which was used to create them.

You could use Invoke if InvokeRequired which will marshal the call to the main thread. Here's a nice article.

But probably the easiest solution would be to simply use a BackgroundWorker because this way you no longer need to manual marshal the calls to the GUI thread. 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();
like image 122
Darin Dimitrov Avatar answered Dec 30 '22 17:12

Darin Dimitrov


In general GUI in C# can be updated only from the same thread it was created if it isn't the same thread than the value of InvokeRequired is true else it false, if it true you call again the same method, but from the same thread the GUI was created

you should use it like this:

 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 additional information

How to update the GUI from another thread in C#?

like image 40
Delashmate Avatar answered Dec 30 '22 16:12

Delashmate