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

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

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the\">Cross-thread操作无效:控制距离大于螺纹以外的线程它是在创建访问


 公共无效CheckUnusedTabs(字符串strTabToRemove)
{
    TabPage的TP = TaskBarRef.tabControl1.TabPages [strTabToRemove]
    tp.Controls.Remove(本);
    TaskBarRef.tabControl1.TabPages.Remove(TP);
}

我想使用上述code在Windows应用程序的TabControl的关闭标签页和我遇到的错误:


  

跨线程操作无效。


如何解决此问题?


解决方案

您只能使从主线程的WinForm控件的变化。你需要检查InvokeRequired是否在控制真正的,然后根据需要调用的方法。

您可以做这样的事情,使其工作:

 公共无效CheckUnusedTabs(字符串strTabToRemove)
{
    如果(TaskBarRef.tabControl1.InvokeRequired)
    {
        TaskBarRef.tabControl1.Invoke(新动作&LT;串GT;(CheckUnusedTabs),strTabToRemove);
        返回;
    }    TabPage的TP = TaskBarRef.tabControl1.TabPages [strTabToRemove]
    tp.Controls.Remove(本);
    TaskBarRef.tabControl1.TabPages.Remove(TP);
}

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 ?

解决方案

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天全站免登陆