Hard killing a thread that's got resources open (SqlDataAdapter, SqlConnection)

  • Thread starter Thread starter Sgt. Sausage
  • Start date Start date
S

Sgt. Sausage

New to multi-threading (less than 24 hours at it <grin>)

Anyway, it's all making sense, and working fairly well
thus far, but I'm having a minor issue I'm not sure how
to get around.

I've got a form that uses SqlDataAdapter. It fires off
a thread to fill a DataSet. Not a big deal, this works.
I've also got a requirement that the Thread that's going
off to do the work -- if it takes too long, it has to
honor a timeout, or a cancellation request from the
user.

No problems here, I've got them both done and working
to where they kill the Thread (Thread.Abort()). The
problem is, that killing the Thread leaves the SqlDataAdapter
in an inconsistent state, in particular, the SqlConnection
for the Procedures (InsertProcedure, UpdateProcedure, etc) --
the SqlConnection is still open, but hosed and can't be
re-used.

If I try to .Close() it, I get an error. It can't be closed.

What I've done is to, just prior to the Thread.Abort(), I
issue a Cancel() on the Command object. This seems to have
fixed most of the issue, but not all. The Cancel() appears
to only *attempt* a true cancel of the command, and is not
actually successful every time. Of course, the other issue
is that .Cancle returns void, so I don't have a return
value to check if it actually was successful.

So, I do

theCommand.Cancel()
Thread.Abort()

and hope that the Command gets cancelled. Sometimes it's
not. This leaves me holding the bag, as the next time
the Adapter attempts to do something on that connection,
it's hosed. There's a lot of data access going on with
this form, so I keep reusing the same connection. That
gets to be a problem when you try to reuse a hosed
connection.

Are you following me on this?

What's a guy to do?
 
I don't think aborting a thread like this is a good idea (I've been through
the wringer with almost exactly the same issue). I think aborting any .NET
thread that is making use of COM resources is generally considered bad
practice with unpredictable results. Cancel the command by all means, but
let the thread run through to terminate normally.
 
Robin Tucker said:
I don't think aborting a thread like this is a good idea (I've been
through the wringer with almost exactly the same issue). I think aborting
any .NET thread that is making use of COM resources is generally
considered bad practice with unpredictable results. Cancel the command by
all means, but let the thread run through to terminate normally.

Yeah, I suppose that's the route to go.

I'll have to change a few things to do this, but it's TheRightThingToDo(tm).
 
Back
Top