【问题标题】:Closing form from another thread从另一个线程关闭表单
【发布时间】:2013-08-21 00:18:31
【问题描述】:

我有这个运行.exe的代码

string openEXE = @"C:\Users\marek\Documents\Visual Studio 2012\Projects\tours\tours\bin\Debug\netpokl.exe";
                 Process b = Process.Start(openEXE);
                 b.EnableRaisingEvents = true;
                 b.Exited += (netpokl_Closed);

当它关闭时,它会调用 netpokl_Closed 方法。问题是当我insert into netpokl_Closed command - this.Close() 这个异常出现时:Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

我该如何解决?感谢您的时间和回答。

【问题讨论】:

    标签: c# multithreading winforms exe


    【解决方案1】:

    您可以使用Delegate 关闭您的表单

          public delegate void CloseDelagate(); 
    
          Form1.Invoke(new CloseDelegate(Form2.Close));
    

    【讨论】:

    • 这可能会抑制异常被抛出,但它可能会在运行时使应用程序崩溃。
    【解决方案2】:

    您收到异常是因为您试图从一个线程关闭表单,而不是在它创建的地方。这是不允许的。

    这样做

    this.Invoke((MethodInvoker) delegate
            {
                // close the form on the forms thread
                this.Close();
            });
    

    【讨论】:

      【解决方案3】:

      当控件的创建线程以外的线程尝试访问该控件的方法或属性之一时,通常会导致不可预知的结果。常见的无效线程活动是在访问控件的 Handle 属性的错误线程上调用

      获取或设置一个值,该值指示在调试应用程序时是否捕获访问控件的 Handle 属性的错误线程上的调用。

      看看

      http://msdn.microsoft.com/en-us/library/system.windows.forms.control.checkforillegalcrossthreadcalls.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 2015-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多