Search code examples
c#multithreadinguser-controlsinvokerequired

C# windows forms custom controls cross-thread operation


I have one main windows form and within that form I have custom controls that represents different screens in application. I want to access this control's child controls. There's something I'm not getting here...sometimes I get this error:

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

but sometimes everything works OK. I don't completelly understand why the error...probably something with external device (MEI BillAcceptor) which has an event (inside Form1 class) that does the changes to the control... so let me write a simple code...

//user control
public partial class Screen2 : UserControl
{
    public void changeValue(string txt)
    {
        lblText.Text = txt;
    }
}

and the method changeValue is called from a form1 when particular event is rised...

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        BillAcceptor.SomeBillAcceptorEvent += 
            new SomeBillAcceptorEventHandler(changeText);
    }

    private void changeText(object sender, EventArgs args)
    {
        _screen2.changeValue("some text");
    }
}

So the most annoying thing is that sometimes everything actually works... So my question is "do I have to use Invoke here?" or how do I solve this with less changes to the application...


Solution

  • Yes you need to use Invoke if there is a possibility of that method being called from a different thread.

    You can check this.InvokeRequired(), if true, then use invoke, if false do a normal call.