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??
ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.
When this method is invoked on a thread, the system throws a ThreadAbortException in the thread to abort it. ThreadAbortException is a special exception that can be caught by application code, but is re-thrown at the end of the catch block unless ResetAbort is called.
Abort may prevent the execution of static constructors or the release of managed or unmanaged resources. For this reason, Thread. Abort always throws a PlatformNotSupportedException on .
Console. WriteLine("Stop thread");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With