Thread.Abort and Finally block question

  • Thread starter Thread starter cottonviking
  • Start date Start date
C

cottonviking

Greetings, all! I've been pondering the pitfalls of aborting a
secondary thread in a service app I'm writing (VB, fx v1.1).
Everything I've read so far pretty much dissuades one from aborting one
thread from another, and I'm almost at the point of acquiescing but
curiosity leads me on.

Below is a procedure template that I wonder might guarantee behavior
during an abort, and I'd like to get some feedback in case it's just
plain nonsense.

Private Sub WorkerThread()
Dim finallyDone As Boolean = false
Try
'
' do some stuff
'
Catch ex As Exception
'
' do something exceptional
'
Finally
'
' Question: Would the following loop insure
' completion of the Finally block even
' if an abort exception occurred during
' execution of the block?
'
Do Until finallyDone
Try
'
' do work that *has* to complete, even if it
' means taking more than one run at it
'
finallyDone = True
Catch ex As Exception
'
' do something exceptional, like
' Thread.ResetAbort()
'
End Try
Loop
End Try
End Sub

In my particular situation, I want to raise an event from the Finally
block which passes data from the secondary thread back to the main
thread just before the secondary thread ends, something like this:

Do Until finallyDone
Try
RaiseEvent WorkerThreadEnd(WorkResults)
finallyDone = True
Catch ex As Exception
'
' do something exceptional, like
' Thread.ResetAbort()
'
End Try
Loop

The concern over the possibility of an abort stems from the fact that
the main thread keeps tabs on the time taken by the secondary thread.
If the main thread thinks the secondary thread has timed out, it issues
the Abort request on the secondary thread. No doubt there would come a
time when the secondary thread is one line away from finishing but a
few timeslices beyond the main thread's timeout period. In essence I'm
trying to sidestep the abort if the secondary thread is just moments
from completing, i.e., we just stepped into the Finally block.

Any takers?

TIA, Paul
 
Greetings, all! I've been pondering the pitfalls of aborting a
secondary thread in a service app I'm writing (VB, fx v1.1).
Everything I've read so far pretty much dissuades one from aborting one
thread from another, and I'm almost at the point of acquiescing but
curiosity leads me on.

<snip>

The Finally block will be executed if the AbortException occurs during
the Try block. However, if the AbortException occurs during the Finally
block, the block will be aborted abruptly (i.e. without finishing the
Finally block).
 
Thanks for the quick response, Jon. That's what I was afraid of but
makes sense. So much for Thread.Abort then!
 
Back
Top