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

If you are getting this exception it means that your are trying to access a Control - running on the main thread of your application, say ThreadA - from another thread, ThreadB.

This other ThreadB could of-course be either a

System.Threading.Thread

 or a

System.ComponentModel.BackgroundWorker

or whatever.


The way to get around this, is by using invocation in the Control.


Here is a example if you don’t need a return value:

public void AddMessage(MessageType type, Message message)
{
    internalAddMessage(type, message);
}

private void internalAddMessage(MessageType type, Message message)
{
    if (this.InvokeRequired)
    {
        this.Invoke((MethodInvoker)delegate { internalAddMessage(type, message); });
        return;
    }
    //Do the 'Add Message' stuff you want to do
}

or if you need a return value from the Invoked method:

 

private DialogResult internalShowDialog()
{
    if (this.InvokeRequired)
    {
        Func<DialogResult> func = new Func<DialogResult>(internalShowDialog);
        return (DialogResult)this.Invoke(func);
    }
    else
    {
        return this.ShowDialog();
    }
}

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading