is Aborting threads really OK?

  • Thread starter Thread starter Jim
  • Start date Start date
J

Jim

Hi,

I remember from my c++ days that hard terminating a thread is a bad thing,
as it can cause
resource leaks since destructors and clean up code never gets a chance to
get executed.

I'm writing a multithreaded app in C# that has various threads running loops
that poll sockets.
I want to be able to stop the polling thread from a different thread. As far
as I know, there are two
ways to do this:

1. Create a bool instance member protected by a Mutex that the Stop() method
will set to false. The thread
that needs to be stopped will simply check the value of this bool on each
loop.
2. call the thread's Abort() method.

I would surely like to avoid having to deal with the bool instance member
and the mutex wait/release calls if I could,
but calling Abort just feels naughty. Also, if my thread is in a blocking
socket receive call, it might never loop back around to figure out that it
should terminate. I know the garbage collector should in theory be able to
detect when objects can
be released, but is it completely solid? Also, in regards to sockets, if I
kill a thread that has a socket making a blocking call in it, am I somehow
leaking a socket resource?

-Jim
 
Aborting or terminating a thread from another thread is always a bad
practice. Specially as the product/project progresses and becomes more
complex you will run into all sorts of negative side-effects. We did that in
C++ project end ended up in a situation that we had randomly GPE failures,
etc.

So find an easy way to signal to the thread that it should end graciously.

Regards, Klaus
-----------------------------------------------
Klaus Salchner
email: (e-mail address removed)

Proud member of
http://linkedin.com - become part of my professional network; it's a free
3rd party tool
http://gotdotnet.com
http://theserverside.net
 
Hi Jim,

I strongly recommend you use the synchronized object to stop another thread
and suggest not use Thread.Abort to terminate other threads. Because
calling Abort on another thread is akin to throwing an exception on that
thread, without knowing what point that thread has reached in its
processing.

Here is article, you may take a look.

Managed Threading Best Practices
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm
l/cpconmanagedthreadingbestpractices.asp

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top