栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

实现C#通用超时

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实现C#通用超时

这里真正棘手的部分是通过将执行程序线程从Action传递回可能中止的位置来杀死长期运行的任务。我通过使用包装的委托来完成此任务,该委托将线程传递出去以杀死生成lambda的方法中的局部变量。

我提交了这个示例,供您欣赏。您真正感兴趣的方法是CallWithTimeout。
这将通过中断长时间运行的线程并吞下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);    }

工作的静态方法:

    static void CallWithTimeout(Action action, int timeoutMilliseconds)    {        Thread threadToKill = null;        Action wrappedAction = () =>        { threadToKill = Thread.CurrentThread; try {     action(); } catch(ThreadAbortException ex){    Thread.ResetAbort();// cancel hard aborting, lets to finish it nicely. }        };        IAsyncResult result = wrappedAction.BeginInvoke(null, null);        if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))        { wrappedAction.EndInvoke(result);        }        else        { threadToKill.Abort(); throw new TimeoutException();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442822.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号