Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solve a cross-threading Exception in WinForms

Presently I'm working with WinForms(in C#) and I have to run the application in the background. For this purpose I'm using asynchronous. When I run the application it's showing an exception like

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

How can I solve this error?

like image 446
Victor Avatar asked May 03 '11 11:05

Victor


People also ask

What is cross threading in C#?

If it's created on another thread then it will execute the second line. In the second line we create a MethodInvoker with the name of AssignMethodToControl which is a delegate that executes a method that has no parameters. In the third line we invoke the MethodInvoker to the Control.

What is InvokeRequired in C#?

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. public: property bool InvokeRequired { bool get(); }; C# Copy.

Are GUI controls multithreading safe?

Multithreading can improve the performance of Windows Forms apps, but access to Windows Forms controls isn't inherently thread-safe. Multithreading can expose your code to serious and complex bugs.


2 Answers

When making method calls to a control, if the caller is on a different thread than the one the control was created on, you need to call using Control.Invoke. Here is a code sample:

// you can define a delegate with the signature you want
public delegate void UpdateControlsDelegate();

public void SomeMethod()
{
    //this method is executed by the background worker
    InvokeUpdateControls();
}

public void InvokeUpdateControls()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new UpdateControlsDelegate(UpdateControls));
    }
    else
    {
        UpdateControls();
    }
}

private void UpdateControls()
{
    // update your controls here
}

Hope it helps.

like image 94
Daniel Peñalba Avatar answered Oct 11 '22 10:10

Daniel Peñalba


Most often, the best way to do this sort of thing with WinForms is to use BackgroundWorker, which will run your work on a background thread, but provide you with a nice clean way to report status back to the UI.

In a lot of everyday .NET programming, explicitly creating threads or calling .Invoke is a sign that you're not using the framework to its full advantage (of course, there are lots of legitimate reasons to do low-level stuff too, it's just that they're less common that people sometimes realise).

like image 27
Will Dean Avatar answered Oct 11 '22 12:10

Will Dean