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

别来无恙 提交于 2019-11-28 02:02:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!