check if thread finished its method before “killing” it c#

前端 未结 1 918
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 02:44

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 loopi

相关标签:
1条回答
  • 2020-12-07 03:29

    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.

    0 讨论(0)
提交回复
热议问题