.NET Thread.Abort again

Posted by hoodoos on Stack Overflow See other posts from Stack Overflow or by hoodoos
Published on 2010-01-18T09:30:48Z Indexed on 2010/03/14 18:25 UTC
Read the original article Hit count: 327

Filed under:
|
|

Again I want to talk about safety of the Thread.Abort function. I was interested to have some way to abort operations which I can't control really and don't want actually, but I want to have my threads free as soon as possible to prevent thread thirsty of my application.

So I wrote some test code to see if it's possible to use Thread.Abort and have the aborting thread clean up resources propertly. Here's code:

int threadRunCount = 0;
int threadAbortCount = 0;
int threadFinallyCount = 0;
int iterations = 0;

while( true )
{
 Thread t = new Thread( () =>
 {
  threadRunCount++;
  try
  {
   Thread.Sleep( Random.Next( 45, 55 ) );
  }
  catch( ThreadAbortException )
  {
   threadAbortCount++;
  }
  finally
  {
   threadFinallyCount++;
  }
 } );

 t.Start();
 Thread.Sleep( 45 );
 t.Abort();

 iterations++;
}

So, so far this code worked for about 5 mins, and threadRunCount was always equal to threadFinally and threadAbort was somewhat lower in number, because some threads completed with no abort or probably got aborted in finally.

So the question is, do I miss something?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about threading