Naveen's Weblog

Bridge to future

Aborting a suspended thread

Posted by codingsense on March 16, 2010


Hi,

I was working on a multithreading application and found an interesting thing on resuming a thread, so planned to share with you.

When a thread is running if we abort it, it gets stopped. But if a suspended thread is aborted then it gives an exception “Thread is suspended; attempting to abort”.

The below sample demonstrates it, first the thread is started, then suspended and then aborted. Run the application and check the error.




using System;
using System.Threading;

namespace ConsoleApplication1
{
class Program    
{
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(DoSomething));
thread.Start();

for (int Index = 0; Index < 10; Index++)
{
switch (Index)
{
case 4:
thread.Suspend();
Console.WriteLine("Thread suspended");
break;

case 6:
thread.Abort();
Console.WriteLine("Thread aborted");
break;

}

//Main Thread is made to sleep                
Thread.Sleep(300);
}

Console.Read();
}

private static void DoSomething()
{
while (true)
{
Thread.Sleep(300);
Console.WriteLine("I am busy doing work");
}
}
}
}


To overcome this exception we can use Resume to invoke the suspended thread and then abort.
Replace the case 6 with below code snippet.




case 6:
try                        
{
thread.Abort();
}
catch (ThreadStateException)
{
thread.Resume();
}
Console.WriteLine("Thread aborted");
break;


now running the application aborts the thread as expected.
From this sample we can learn that if we use resume on a suspended thread then it starts again, but if we have signalled for abort on that thread and try resume then it will stop the thread in proper manner.

Happy Learning
Codingsense 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: