在.NET线程中止线程、NET

2023-09-03 01:35:30 作者:帅瞎你的狗眼

我有一个线程,多数民众赞成分析文件,使事务对数据库的调用,每笔交易都有一个审核项作为交易的一部分。有什么大大不妥调用Thread.Abort的()来停止文件的处理?而不是分散难看的安全点行吗?

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.

推荐答案

最明显的问题是放弃交易,这可能会导致阻塞不确定的时间(或直到超时)的风险。但是你可以把所有的排序的关一塌糊涂 - 不可恢复显示器锁,信号量等,内存泄漏等

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.