C#如何控制方法的执行时间,超时则强制退出方法执行
2013-08-30 17:21
411 查看
有时候我们需要控制方法的执行时间,如果超时则强制退出。
要控制执行时间,我们必须使用异步模式,在另外一个线程中执行方法,如果超时,则抛出异常终止线程执行。
如下使用异步执行委托的方式实现,使用WaitHandle的WaitOne方法来计算时间超时:
要控制执行时间,我们必须使用异步模式,在另外一个线程中执行方法,如果超时,则抛出异常终止线程执行。
如下使用异步执行委托的方式实现,使用WaitHandle的WaitOne方法来计算时间超时:
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; action(); }; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { wrappedAction.EndInvoke(result); } else { threadToKill.Abort(); throw new TimeoutException(); } }}
相关文章推荐
- C#如何控制方法的执行时间,超时则强制退出方法执行
- C# 给某个方法设定执行超时时间 C#如何控制方法的执行时间,超时则强制退出方法执行 C#函数运行超时则终止执行(任意参数类型及参数个数通用版)
- C#如何控制方法的执行时间,超时则强制退出方法执行
- 如何获取C#中方法的执行时间以及其代码注入详解
- C# 给某个方法设定执行超时时间
- 如何控制C#Socket的连接超时时间
- C# 给某个方法设定执行超时时间
- C# 给某个方法设定执行超时时间
- C# 给某个方法设定执行超时时间
- C#在VS2005开发环境中利用异步模式来对一个方法的执行时间进行超时控制
- C# 给某个方法设定执行超时时间
- C# 给某个方法设定执行超时时间-2
- C# 给某个方法设定执行超时时间
- 转 C# 给某个方法设定执行超时时间
- 如何控制一个函数的执行时间
- C#计算代码执行时间的方法
- C#中如何执行存储过程方法
- 如何精确计算一个方法执行的时间-如博客园的提交评论提交耗时xxx毫秒?
- C#: 一个方法执行超时 timeout 检查的实现
- c# 计算程序执行时间方法