获取跨线程操作无效 [英] Getting Cross-thread operation not valid

查看:119
本文介绍了获取跨线程操作无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

跨线程操作无效:从线程以外的线程访问的控制创建的线程

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);
} 

我试图关闭Windows应用程序的tabcontrol中的一个标签,使用上述代码,我遇到错误:

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.

如何解决这个问题?

推荐答案

您只能从主人更改WinForm控件线。您需要检查InvokeRequired是否为true,然后根据需要调用该方法。

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);
}

这篇关于获取跨线程操作无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆