Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any solution to Illegal Cross Thread Operation exception?

When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception.

Is there anyway to prevent this?

like image 221
gil Avatar asked Aug 05 '08 07:08

gil


2 Answers

You should be able to do something like:

if (control.InvokeRequired)
{
    control.Invoke(delegateWithMyCode);
}
else
{
    delegateWithMyCode();
}

InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread.

UPDATE: Actually, at my last job we did something like this:

private void SomeEventHandler(Object someParam)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam);
    }

    // Regular handling code
}

which removes the need for the else block and kind of tightens up the code.

like image 155
Mike Stone Avatar answered Oct 04 '22 23:10

Mike Stone


As I don't have a test case to go from I can't guarantee this solution, but it seems to me that a scenario similar to the one used to update progress bars in different threads (use a delegate) would be suitable here.

public delegate void DataBindDelegate();
public DataBindDelegate BindData = new DataBindDelegate(DoDataBind);

public void DoDataBind()
{
    DataBind();
}

If the data binding needs to be done by a particular thread, then let that thread do the work!

like image 42
tags2k Avatar answered Oct 04 '22 21:10

tags2k