超时模式 - Thread.Abort 到底有多糟糕? [英] Timeout Pattern - How bad is Thread.Abort really?

查看:24
本文介绍了超时模式 - Thread.Abort 到底有多糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在各种网站上都读到 Thread.Abort 不太好用.在这种情况下,您如何实现超时模式?例如,我读到 MS 在整个框架中使用以下模式(我已将其包装在扩展方法中).就个人而言,我认为这是一个非常酷的扩展,但我担心 Thread.Abort.有人有更好的方法吗?

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;
        }
    }

推荐答案

可能很糟糕.

中止的线程可能使共享状态损坏,可能使异步操作继续运行,......

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

参见 Joe Duffy 的博客:托管代码和异步异常强化".

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

这篇关于超时模式 - Thread.Abort 到底有多糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆