Thread Abort in .NET

2019-06-28 05:23发布

问题:

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