Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if thread finished its method before "killing" it c#

I have 2 threads in my program. 1 is handling a GUI and the other is doing some word automation. Lets call them GUIThread and WorkerThread.

The WorkerThread is looping through methods using recursion. The WorkerThread is only alive while doing the word automation and the user must be able to stop the word automation. Therefore I have implemented a "Stop" button on the GUI which simply kills/terminates the WorkerThread. However if I kill the WorkerThread while it's in the middle of a method it sometimes causes a problem in my word document (this is a longer story) and that's why I want to check if the WorkerThread has finished/returned from a method before I kill it.

This is what my code does when I hit the "Stop" button:

//Stops the worker thread = stops word automation in process
workerThread.Abort();

//This blocks the thread until the workerThread has aborted
while (workerThread.IsAlive) ;

My own suggestion/workaround for the problem was to have a global variable I could set each time the WorkerThread entered and left a method but this doesn't seem right to me. I mean I think there must be an easier way to deal with it.

like image 905
n.Stenvang Avatar asked Dec 19 '22 08:12

n.Stenvang


1 Answers

However if I kill the WorkerThread while it's in the middle of a method it sometimes causes a problem in my word document

This is why you should never kill a thread. You can't say what the thread was doing, whether it is safe to kill? etc etc.

Abort isn't doing what you expect it to do. Look at the documentation, it is subtle Calling this method usually terminates the thread. Note the word usually and not always.

Yes, Abort will not kill the thread always. For example if the thread was running unmanaged code, CLR will not abort the thread, instead it will wait for the thread to return to managed code.

Sameway Abort will not do its job when thread is in Constrained Execution Region, finally blocks etc.

The CLR delays thread aborts for code that is executing in a CER.

For example: Try to run the following code and see what happens.

private void IWillNeverReturn()
{
    Thread thread = new Thread(() =>
    {
        try
        {
        }
        finally
        {
            while (true)
            { }
        }
    });
    thread.Start();

    Thread.Sleep(1000);
    thread.Abort();
}

Let the thread decide when it should complete, Tell the thread that it should stop as soon as it can. You tell it using CancellationToken.

If you google for Thread.Abort Evil, you'll find lot of useful resources, Here is one.

like image 72
Sriram Sakthivel Avatar answered Feb 09 '23 14:02

Sriram Sakthivel