简体   繁体   English

如何在程序关闭时强制所有程序线程退出?

[英]How can I force all program threads to exit on program close?

关闭主窗口后,如何确保所有程序线程都中止?

You can set the "IsBackground" Property to true. 您可以将“IsBackground”属性设置为true。 The CLR closes all background threads when the application exits. CLR在应用程序退出时关闭所有后台线程。

  • If you have designed the threading well, you should have a mechanism to close them - eg use a ManualResetEvent to signal them to close 如果你已经很好地设计了线程,你应该有一个机制来关闭它们 - 例如使用ManualResetEvent来指示它们关闭
  • You can Thread.Join to wait until they close, or Thread.Abort to have them abort in a nasty way 你可以让Thread.Join等到它们关闭,或者Thread.Abort让它们以令人讨厌的方式中止
  • If they are background threads, they will close when the app does 如果它们是后台线程,它们将在应用程序关闭时关闭

See also: http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.80).aspx 另见: http//msdn.microsoft.com/en-us/library/7a2f3ay4(v = vs.80).aspx

Try 尝试

Application.ExitThread();
Environment.Exit(0);

or 要么

Dispatcher.CurrentDispatcher.Thread.Abort();

Set the IsBackground property to true,and add the following lines: IsBackground属性设置为true,并添加以下行:

AppDomain.CurrentDomain.ProcessExit += CloseMe; // for the main process
AppDomain.CurrentDomain.DomainUnload += CloseMe; // for ApplicationDomains

Let the CloseMe method set a flag which is checked in the main loop of the thread. CloseMe方法设置一个在线程的主循环中检查的标志。

Collect them somewhere, such as 将它们收集到某处,例如

static public List<Thread> AllThreads;

and use that collection to .Abort() them, one by one. 并将该集合.Abort()用于.Abort()它们。

This is the HARD and WRONG way. 这是艰难错误的方式。 Better would be to signal them to stop somehow, and then .Join() one by one. 更好的方法是让他们以某种方式停止,然后一个接一个地进行.Join()

By letting the program actually close, ie. 通过让程序实际关闭,即。 dont deliberately introduce any code that forces the thread that runs the main window to wait for any other threads. 不要故意引入任何强制运行主窗口的线程等待任何其他线程的代码。 The thread that runs the main window will then be free to exitProcess() and the OS will then abort all other threads in your process, no matter what they are doing. 然后,运行主窗口的线程可以自由地使用exitProcess(),然后操作系统将中止进程中的所有其他线程,无论它们在做什么。

Rgds, Martin Rgds,马丁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM