我可以放心地依靠的IsBackground在线程当应用程序终止

我可以放心地依靠的IsBackground在线程当应用程序终止

本文介绍了我可以放心地依靠的IsBackground在线程当应用程序终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行GUI中的一些后台线程。目前我实现了个人线程取消code,但没有在线程的IsBackground财产,并根据MSDN他们会取消自己。

I'm running some background threads in the GUI. Currently I'm implementing a personal Thread cancellation code but there is IsBackground property in threads and according MSDN they'll cancel themselves.

我知道,这将Thread.Abort的(),这是肮脏的,但有什么事情在我需要保持一个正确的状态,或该后台线程需要适当的清理工作。

I know that it's going to Thread.Abort() which is nasty but there is nothing going in this background threads that I need to keep a proper state or requires proper clean-up.

我试图避免任何崩溃,如果用户只是倒闭在后台线程的应用当中。由于多线程情况下是相当难以测试我想获得你对这个问题的看法。

I'm trying to avoid any crashes if the user just closes down the application in the middle of a background thread. Since multi-threading scenarios are quite hard to test I'd like to get your opinion on the subject.

基本上,而不是我自己的滚动code应我只是设置的IsBackground = TRUE,忘了休息吗?

Basically, instead of rolling my own code shall I just set IsBackground = True and forget about the rest?

推荐答案

Thread.Abort的抛出一个异常,所以如果你的code已经正确地写入到使用最后/使用,它应该会失败优雅,释放所有的资源。

Thread.Abort throws an exception, so if your code is already correctly written to use finally/using, it should fail gracefully and release all resources.

修改

我也许应该给更多的细节。首先,异常的类型ThreadAbortException的。有趣的是,即使你抓住它,什么也不做,它不会消失。换句话说,一旦它离开你的catch块,但它仍然被抛出。这是为了让捕捉异常和吞咽它的(通常是坏)的做法并没有从得到中止停止线程。如果你真的想停止中止,你需要捕捉异常,然后调用Thread.ResetAbort。

I should probably give a little more detail. First, the exception is of type ThreadAbortException. The interesting thing is that, even if you catch it and do nothing, it doesn't go away. In other words, as soon as it leaves your catch block, it continues to be thrown. This is so that the (typically bad) practice of catching Exception and swallowing it doesn't stop the thread from getting aborted. If you do actually want to stop the abort, you need to catch the exception, then call Thread.ResetAbort.

这篇关于我可以放心地依靠的IsBackground在线程当应用程序终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:38