13

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

public void CheckUnusedTabs(string strTabToRemove)
{ 
    TabPage tp = TaskBarRef.tabControl1.TabPages[strTabToRemove];
    tp.Controls.Remove(this);
    TaskBarRef.tabControl1.TabPages.Remove(tp);
} 

I am trying to close a tab in the tabcontrol of windows application using the above code and i encountered the error:

Cross-thread operation not valid.

How to solve this ?

Community
  • 1
  • 1
Anuya
  • 8,082
  • 49
  • 137
  • 222

5 Answers5

25

You can only make changes to WinForm controls from the master thread. You need to check whether InvokeRequired is true on the control and then Invoke the method as needed.

You can do something like this to make it work:

public void CheckUnusedTabs(string strTabToRemove)
{ 
    if (TaskBarRef.tabControl1.InvokeRequired)
    {
        TaskBarRef.tabControl1.Invoke(new Action<string>(CheckUnusedTabs), strTabToRemove);
        return;
    }      

    TabPage tp = TaskBarRef.tabControl1.TabPages[strTabToRemove];
    tp.Controls.Remove(this);
    TaskBarRef.tabControl1.TabPages.Remove(tp);
}
JDunkerley
  • 12,355
  • 5
  • 41
  • 45
  • FYI, your clear update of the original code was the only way I was able to figure out how to properly implement this in mine. Thanks. – Jason Dec 18 '12 at 16:29
20

call using invoke, because you're accessing the GUI thread using another thread

 this.Invoke((MethodInvoker)delegate() {CheckUnusedTabs(""); });
mustafabar
  • 2,317
  • 6
  • 31
  • 47
5

When using threads and UI controls, in winforms, you need to use InvokeRequired to make changes to the controls.

EDIT.

added an example.

Form, with button and label.

try

private void button2_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(UpdateProcess);
            thread.Start();
        }

        private void SetLabelText(string val)
        {
            label1.Text = val;
        }
        delegate void m_SetLabel(string val);

        private void UpdateProcess()
        {
            int i = 0;

            while (true)
            {
                if (label1.InvokeRequired)
                {
                    m_SetLabel setLabel = SetLabelText;
                    Invoke(setLabel, i.ToString());
                }
                else
                    label1.Text = i.ToString();
                i++;
                Thread.Sleep(500);
            }
        }
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
1

Cross thread not valid exception is due to the UI controls being accessed from other threads than main thread.see this http://helpprogramming.blogspot.com/2011/10/invalid-cross-thread-operation.html

art
  • 11
  • 1
-3

Set the following variable:

CheckIllegalCrossThreadValidation = false
Steve Guidi
  • 19,700
  • 9
  • 74
  • 90
maxy
  • 438
  • 3
  • 10
  • 20