Check if the thread completed its method before it "killed" it C #

I have 2 threads in my program. 1 handles a graphical interface, while the other handles some word automation. Lets call them GUIThread and WorkerThread.

WorkerThread executes a loop using recursion. WorkerThread only works with word automation, and the user should be able to stop word automation. So I applied the “Stop” button in the GUI, which simply kills / terminates WorkerThread. However, if I kill WorkerThread while it is in the middle of the method, this sometimes causes a problem in the document with my word (this is a longer story), and therefore I want to check if WorkerThread has finished / returned from the method before I kill it .

This is what my code does when I click 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 that I could set each time I entered WorkerThread and leave the method, but that doesn't seem right to me. I mean, I think there should be an easier way to handle this.

+4
source share
1 answer

However, if I kill WorkerThread while it is in the middle of the method, this sometimes causes a problem in the Word document

That is why you should never kill a thread. You cannot say what the stream was doing, is it possible to kill it? etc.

Abort , . , . . .

, Abort . , , CLR , .

Sameway Abort , , - ..

CLR , CER.

: , .

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

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

, . , , . , CancellationToken.

google Thread.Abort Evil, , .

+10

Source: https://habr.com/ru/post/1568282/


All Articles