简体   繁体   English

线程在.NET中止

[英]Thread Abort in .NET

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? 调用Thread.Abort()来停止处理文件有什么大不了的错吗? 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. 但你可以把各种各样的东西弄得一团糟 - 不可恢复的Monitor锁,信号量等,内存泄漏等。

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. 而你能够知道它正在做什么的唯一方法就是它已经处于一个已知的“安全点”(使用你的术语) - 所以你也可以抛出异常或其他东西让它以管理的方式自我提升。

最佳实践:仅在拆除过程时中止线程。

Try Thread.Interrupt() to force the thread to exit from its wait state. 尝试Thread.Interrupt()以强制线程退出其等待状态。

MSDN page MSDN页面

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

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