views:

303

answers:

2

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.

+8  A: 

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.

Marc Gravell
The session the transactions are running in will be closed down, and the class that the thread was running in will be disposed. Meaning the server will rollback the transaction, and the class can be properly closed down from the cancel function. What locks, semaphores, etc will be lost?
Will
@Will: An abort can occur while your cleanup is being executed. Which can mean that your cleanup *will not finish*. Also, an Abort can disrupt a lock statement (there are some safeguards, but there are no guarantees it won't). So you could end up with a lock that won't be unlocked again.
Ruben
@Ruben: Thread abort will not interrupt cleanup logic: "We don’t process thread aborts if you’re executing inside a Constrained Execution Region (CER), finally block, catch block, .cctor, or while running inside unmanaged code. If an abort is requested while inside one of these regions, we process it as soon as you exit (assuming you’re not nested inside another)." Joe Duffy.
Sergey Teplyakov
@Sergey: Unfortunately, those are not the only places where cleanup can occur. For example, a `lock(x)` will look like `Monitor.Enter(x) try { ... } finally { Monitor.Exit(x); }` which means that an Abort can occur between Enter and try. Also, there is no guarantee that cleanup code is inside finally etc., it can also be code which doesn't expect exceptions to be thrown (because it appears to be exception safe, if asynchronous exceptions are ignored, or it is setup code setting flags which are to be used by the cleanup code). Abort makes all these things very complicated to get right.
Ruben
@Ruben: I absolutely agree, that dealing with asynchronous exceptions is very dangerous and error prone.
Sergey Teplyakov
+7  A: 

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

Eric Lippert
Isn't this true for the AppDomanain also?
Pop Catalin