Timeout Pattern - How bad is Thread.Abort really?

最后都变了- 提交于 2019-11-26 04:27:38

问题


I\'ve read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I\'ve read that MS uses the pattern below (which I\'ve wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I\'m worried about the Thread.Abort. Does anyone have a better way?

 public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }

回答1:


Potentially very bad.

The aborted thread could leave shared state corrupted, could leave asynchronous operations running, ...

See Joe Duffy's blog: "Managed code and asynchronous exception hardening".




回答2:


Basically you're talking about aborting an action which (as far as we know) has no graceful way of aborting.

That means there's going to be no safe way of aborting it. Thread.Abort is just not a nice thing to do - there are various race conditions and ugly situations you can get into (see the link in Richard's answer). I would try desperately hard to avoid wanting to cancel actions that don't know about cancellation - and if you absolutely have to do it, consider restarting the whole app afterwards, as you may no longer be in a sane state.




回答3:


It's bad because the thread might be in an inconsistent state or in the middle of some work, and not have the opportunity to clear itself up.

To close it properly, you signal for it to stop what it's doing by calling a method or setting a property, then do Thread.Join to wait until it closes before closing your application or moving onto other tasks.



来源:https://stackoverflow.com/questions/710070/timeout-pattern-how-bad-is-thread-abort-really

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