简体   繁体   English

如何防止因应用程序终止而导致线程中止?

[英]How to prevent aborting of thread due to app termination?

如果例程通过System.Threading.Timer定期运行,如何防止该例程因主机应用程序终止而中止?

Well, you cannot possibly do anything if the application is terminating;好吧,如果应用程序正在终止,您就不可能做任何事情; however you can prevent the implicit application termination by exit from main (closing the main window, etc.) if you open a non-background thread.但是,如果您打开非后台线程,您可以通过从main退出(关闭主窗口等)防止隐式应用程序终止。

You can make the timer to run at that thread, however you cannot do it with System.Threading.Timer , as it runs on thread pool threads (which are background ones).您可以使计时器在该线程上运行,但是您不能使用System.Threading.Timer执行此操作,因为它在线程池线程(后台线程)上运行。 You can eg start a dispatcher on that thread and run a DispatcherTimer (if you are using WPF).例如,您可以在该线程上启动调度程序并运行DispatcherTimer (如果您使用的是 WPF)。

There is no way to guarantee that your thread won't be terminated abnormally.无法保证您的线程不会异常终止。 Any number of things can go wrong: an unexpected power failure, user terminating the application with Task Manager, or a bug in your program that crashes the thread are just three possibilities.很多事情都可能出错:意外断电、用户使用任务管理器终止应用程序,或者程序中的错误导致线程崩溃,这只是三种可能。

If you're doing a multi-stage database update that, if interrupted, would leave your database in a corrupted or inconsistent state, then you should be using transactions.如果您正在执行多阶段数据库更新,如果中断会使您的数据库处于损坏或不一致的状态,那么您应该使用事务。

This code should cause the main thread to block for 10 seconds waiting for any queued timer callbacks to finish.此代码应导致主线程阻塞 10 秒,等待任何排队的计时器回调完成。 This can be run at the exit point of the host application.这可以在主机应用程序的出口点运行。

Dim waitHnd As WaitHandle = New AutoResetEvent(False)
Timer1.Dispose(waitHnd)
waitHnd.WaitOne(10000)

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

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