views:

42

answers:

2

I am initializing a thread as static thread as shown below

Thread GenerateKeywords; private void btnStart_Click(object sender, EventArgs e)

{

    //Initializes the Test Thread           
    Test = new Thread(TestMethod);

    //Sets the apartment state to Static
    Test.SetApartmentState(ApartmentState.STA);

    //Starts the GenerateKeywords Thread           
    Test.Start();

}

but when I am aborting this thread via this method

private void btnStop_Click(object sender, EventArgs e)

{

 if (Test != null)
         Test .Abort();

}

It is giving following exception : " A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll The thread 0x13dc has exited with code 0 (0x0). "

How to get rid of this exception??

+3  A: 

You should poll for some condition while running a thread so as to abort it.Set some boolean variable at button stop and then poll it inside thread method to abort it.

Sandeep
+1  A: 

The ThreadAbort Exception should not be a problem. An unhandled ThreadAbortException is one of only two types of exception that does not cause application shutdown (the other is AppDomainUnloadException).

wrap it in a try catch and handle exception of type ThreadAbort and set Thread.ResetAbort = true;

Check this link for more details.

Vinay B R