Getting Cross-thread operation not valid [duplicate]
Solution 1:
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);
}
Solution 2:
call using invoke, because you're accessing the GUI thread using another thread
this.Invoke((MethodInvoker)delegate() {CheckUnusedTabs(""); });
Solution 3:
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);
}
}
Solution 4:
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