C# 从另一个线程关闭表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18309785/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:52:20  来源:igfitidea点击:

Closing form from another thread

c#multithreadingwinformsexe

提问by Marek

I have got this code which runs an .exe

我有这个代码运行 .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);

And when it closes it calls method netpokl_Closed. The issue is when I insert into netpokl_Closed command- this.Close()this exception rises: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

当它关闭时,它调用方法 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

How can I fix it ? Thank you for your time and answers.

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

采纳答案by Ehsan

You are getting the exception because you are trying to close the form from a thread other than on what it was created on. This is not allowed.

您收到异常是因为您试图从线程关闭表单而不是在创建表单的线程上关闭表单。这是不允许的。

do it like this

像这样做

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

回答by Rohit

You can close your form using Delegate

您可以使用关闭表单 Delegate

      public delegate void CloseDelagate(); 

      Form1.Invoke(new CloseDelegate(Form2.Close));

回答by Andrew

When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property

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

Gets or sets a value indicating whether to catch calls on the wrong thread that access a control's Handle property when an application is being debugged.

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

have a look at

看一下

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

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