Thread Abort in .NET

亡梦爱人 提交于 2019-12-12 11:18:00

问题


I have a thread thats analyzing a file and making transactional calls to the database, each transaction has a audit entry as part of its transaction. Is there anything vastly wrong with calling Thread.Abort() to stop the processing of the file? Rather than scatter ugly safe spots everywhere?

The file will be closed after the Abort call.


回答1:


The obvious problem would be the risk of abandoning a transaction, which could cause blocking for an indeterminate time (or until timeout). But you could leave all sorts off mess - unrecoverable Monitor locks, semaphores, etc, memory leaks, etc.

In short: try as hard as possible to avoid having to abort a thread unless you know exactly what it is doing at the time. And the only way you could know what it is doing is if it is already in a known "safe spot" (to use your term) - so you might as well just throw an exception or something and let it raise itself in a managed way.




回答2:


Best practice: only abort a thread when you are tearing down the process.




回答3:


Try Thread.Interrupt() to force the thread to exit from its wait state.

MSDN page



来源:https://stackoverflow.com/questions/2180033/thread-abort-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!