Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STA thread Abort Exception

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??

like image 201
Ankush Roy Avatar asked Sep 21 '10 10:09

Ankush Roy


People also ask

What is thread abort 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.

What is the exception that will be thrown if you try to start an aborted thread using start method?

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.

Why is thread abort obsolete?

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 .

How can I stop all threads in C#?

Console. WriteLine("Stop thread");


2 Answers

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.

like image 85
Sandeep Pathak Avatar answered Oct 01 '22 09:10

Sandeep Pathak


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.

like image 23
Vinay B R Avatar answered Oct 01 '22 08:10

Vinay B R