C# 获取跨线程操作无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1523878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Cross-thread operation not valid
提问by Anuya
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:
我正在尝试使用上面的代码关闭 Windows 应用程序的 tabcontrol 中的一个选项卡,但我遇到了错误:
Cross-thread operation not valid.
跨线程操作无效。
How to solve this ?
如何解决这个问题?
采纳答案by JDunkerley
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.
您只能从主线程更改 WinForm 控件。您需要检查控件上的 InvokeRequired 是否为 true,然后根据需要调用该方法。
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);
}
回答by Adriaan Stander
When using threads and UI controls, in winforms, you need to use InvokeRequiredto make changes to the controls.
在使用线程和UI控件时,在winforms中,需要使用InvokeRequired对控件进行修改。
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);
}
}
回答by mustafabar
call using invoke, because you're accessing the GUI thread using another thread
使用 invoke 调用,因为您正在使用另一个线程访问 GUI 线程
this.Invoke((MethodInvoker)delegate() {CheckUnusedTabs(""); });
回答by maxy
Set the following variable:
设置以下变量:
CheckIllegalCrossThreadValidation = false
回答by art
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
跨线程无效异常是由于从主线程以外的其他线程访问 UI 控件。请参阅此 http://helpprogramming.blogspot.com/2011/10/invalid-cross-thread-operation.html