开发者

Thread.Abort vs Thread.Interrupt

If I need to cancel some operation on a thread, when should I use Thread.Abort vs Thread.Interrupt. I read the documentation on it but not sure which scneario should i use a particular call between two.

If there is any thi开发者_如何学Gord way of doing it, please let me knwo about it too with pro and cons.


I would avoid using Thread.Abort at all costs. Its behavior is much safer and predictable since .NET 2.0, but there are still some pretty serious pitfalls with it. Most of the aborts inside managed code can be made safe, but not all of them. For example, I believe there are some subtle problems if an abort request is triggered during the processing of a static constructor. Nevermind, the fact that the out-of-band exception can occur at anytime giving you little control over defining where the safe points for shutdown are located.

There are several acceptable ways to terminate a thread gracefully.

  • Use Thread.Interrupt
  • Poll a stopping flag
  • Use WaitHandle events
  • Specialized API calls

I discuss these methods in my answer here.


Most suggestions are already done, but here's an example how i would do it:

    ManualResetEvent _requestTermination = new ManualResetEvent(false);
    Thread _thread;

    public void Init()
    {
        _thread = new Thread(() =>
         {

             while (!_requestTermination.WaitOne(0))
             {
                 // do something usefull

             }

         }));

        _thread.Start();
    }

    public void Dispose()
    {
        _requestTermination.Set();

        // you could enter a maximum wait time in the Join(...)
        _thread.Join();
    }

This way the dispose will wait until the thread has exited.


If you need a delay within the thread, you shouldn't add Thread.Sleep. Use the WaitOne(delayTime). This way you will never have to wait to terminate it.


I wouldn't use Thread.Abort ever. It causes an exception at an almost arbitrary time.


Be careful with Thread.Interrupt. If you don't build in some waiting or sleeping time the thread won't be interrupted.

Be careful with Thread.Abort. If you catch the ThreadAbortException your thread will terminate right after catch + finally.

(I like to use those methods to send a signal to my thread so that it knows it's terminating time, then clean up and exit.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜