实现C#泛型超时 [英] Implement C# Generic Timeout

查看:170
本文介绍了实现C#泛型超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找好的想法实现一个通用的办法有code一行(或匿名委托)与超时执行。

I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.

TemperamentalClass tc = new TemperamentalClass();
tc.DoSomething();  // normally runs in 30 sec.  Want to error at 1 min

我在寻找可以优雅地在很多地方实施一个解决方案,我的code。与气质code(即我不能改变)进行交互。

I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).

另外,我想有违规的超时code从如有可能进一步执行停止。

In addition, I would like to have the offending "timed out" code stopped from executing further if possible.

推荐答案

真正棘手的部分在这里是通过从操作传递执行程序线程回到它可能被中止的地方查杀长期运行的任务。我与使用传递出的螺纹杀成创建拉姆达方法的局部变量包裹委托的做到了这一点。

The really tricky part here was killing the long running task through passing the executor thread from the Action back to a place where it could be aborted. I accomplished this with the use of a wrapped delegate that passes out the thread to kill into a local variable in the method that created the lambda.

我提出这个例子中,为您的享受。你真正感兴趣的方法是CallWithTimeout。 这将放弃它,吞咽ThreadAbortException 取消长时间运行的线程:

I submit this example, for your enjoyment. The method you are really interested in is CallWithTimeout. This will cancel the long running thread by aborting it, and swallowing the ThreadAbortException:

用法:

class Program
{

    static void Main(string[] args)
    {
        //try the five second method with a 6 second timeout
        CallWithTimeout(FiveSecondMethod, 6000);

        //try the five second method with a 4 second timeout
        //this will throw a timeout exception
        CallWithTimeout(FiveSecondMethod, 4000);
    }

    static void FiveSecondMethod()
    {
        Thread.Sleep(5000);
    }

静态方法做的工作:

The static method doing the work:

    static void CallWithTimeout(Action action, int timeoutMilliseconds)
    {
        Thread threadToKill = null;
        Action wrappedAction = () =>
        {
            threadToKill = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);
        if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
        {
            wrappedAction.EndInvoke(result);
        }
        else
        {
            threadToKill.Abort();
            throw new TimeoutException();
        }
    }

}

这篇关于实现C#泛型超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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