C# 给某个方法设定执行超时时间

   

C# 给某个方法设定执行超时时间

标签: c#nullthreadexceptiontimerclass
5657人阅读 评论(3) 收藏 举报
本文章已收录于:

在某些情况下(例如通过网络访问数据),常常不希望程序卡住而占用太多时间以至于造成界面假死。

在这时、我们可以通过Thread、Thread + Invoke(UI)或者是 delegate.BeginInvoke 来避免界面假死,

但是这样做时,某些代码或者是某个方法的执行超时的时间还是无法操控的。
那么我们又是否有一种比较通用的方法、来设定某一个方法的执行超时的时间,让该其一旦超过指定时间则跳出指定方法、进而继续向下执行呢?

答案当然是肯定的。


delegate.BeginInvoke可以实现代码代码的异步执行,在这种情况下,只要让程序可以等待一个Timespan,如果在Timespan到达之前方法内的代码还没有执行完毕、说明该方法执行超时了。

那么关键的就是“等待一个Timespan”,而恰好.NET 里提供了一些类和方法来实现该功能。我这里选用的是ManualResetEvent.WaitOne(timespan, false);其返回值代码其是否在特定时间内收到信号,而我们恰好可以利用这个布尔值 外加一个标记变量 来判断一个方法是否执行超时。

相关的实现代码如下:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading;  
  6.   
  7. namespace Common  
  8. {  
  9.     public delegate void DoHandler();  
  10.   
  11.     public class Timeout  
  12.     {  
  13.         private ManualResetEvent mTimeoutObject;  
  14.         //标记变量  
  15.         private bool mBoTimeout;  
  16.   
  17.         public DoHandler Do;  
  18.   
  19.         public Timeout()  
  20.         {  
  21.             //  初始状态为 停止  
  22.             this.mTimeoutObject = new ManualResetEvent(true);  
  23.         }  
  24.         ///<summary>  
  25.         /// 指定超时时间 异步执行某个方法  
  26.         ///</summary>  
  27.         ///<returns>执行 是否超时</returns>  
  28.         public bool DoWithTimeout(TimeSpan timeSpan)  
  29.         {  
  30.             if (this.Do == null)  
  31.             {  
  32.                 return false;  
  33.             }  
  34.             this.mTimeoutObject.Reset();  
  35.             this.mBoTimeout = true//标记  
  36.             this.Do.BeginInvoke(DoAsyncCallBack, null);  
  37.             // 等待 信号Set  
  38.             if (!this.mTimeoutObject.WaitOne(timeSpan, false))  
  39.             {  
  40.                 this.mBoTimeout = true;  
  41.             }  
  42.             return this.mBoTimeout;  
  43.         }  
  44.         ///<summary>  
  45.         /// 异步委托 回调函数  
  46.         ///</summary>  
  47.         ///<param name="result"></param>  
  48.         private void DoAsyncCallBack(IAsyncResult result)  
  49.         {  
  50.             try  
  51.             {  
  52.                 this.Do.EndInvoke(result);  
  53.                 // 指示方法的执行未超时  
  54.                 this.mBoTimeout = false;  
  55.             }  
  56.             catch (Exception ex)  
  57.             {  
  58.                 Console.WriteLine(ex.Message);  
  59.                 this.mBoTimeout = true;  
  60.             }  
  61.             finally  
  62.             {  
  63.                 this.mTimeoutObject.Set();  
  64.             }  
  65.         }  
  66.     }  
  67. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Common
{
    public delegate void DoHandler();

    public class Timeout
    {
        private ManualResetEvent mTimeoutObject;
        //标记变量
        private bool mBoTimeout;

        public DoHandler Do;

        public Timeout()
        {
            //  初始状态为 停止
            this.mTimeoutObject = new ManualResetEvent(true);
        }
        ///<summary>
        /// 指定超时时间 异步执行某个方法
        ///</summary>
        ///<returns>执行 是否超时</returns>
        public bool DoWithTimeout(TimeSpan timeSpan)
        {
            if (this.Do == null)
            {
                return false;
            }
            this.mTimeoutObject.Reset();
            this.mBoTimeout = true; //标记
            this.Do.BeginInvoke(DoAsyncCallBack, null);
            // 等待 信号Set
            if (!this.mTimeoutObject.WaitOne(timeSpan, false))
            {
                this.mBoTimeout = true;
            }
            return this.mBoTimeout;
        }
        ///<summary>
        /// 异步委托 回调函数
        ///</summary>
        ///<param name="result"></param>
        private void DoAsyncCallBack(IAsyncResult result)
        {
            try
            {
                this.Do.EndInvoke(result);
                // 指示方法的执行未超时
                this.mBoTimeout = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                this.mBoTimeout = true;
            }
            finally
            {
                this.mTimeoutObject.Set();
            }
        }
    }
}


测试代码如下:

  1. class Program  
  2.     {  
  3.         privatestatic Stopwatch watch;  
  4.         privatestatic System.Threading.Timer timer;  
  5.   
  6.         [STAThread]  
  7.         staticvoid Main(string[] args)  
  8.         {  
  9.             watch =new Stopwatch();  
  10.             Timeout timeout =new Timeout();  
  11.             timeout.Do =new Program().DoSomething;  
  12.             watch.Start();  
  13.             timer =new System.Threading.Timer(timerCallBack, null, 0, 500);  
  14.             Console.WriteLine("4秒超时开始执行");  
  15.             bool bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 4));  
  16.             Console.WriteLine(string.Format("4秒超时执行结果,是否超时:{0}", bo));  
  17.             Console.WriteLine("***************************************************");  
  18.               
  19.             timeout =new Timeout();  
  20.             timeout.Do =new Program().DoSomething;  
  21.             Console.WriteLine("6秒超时开始执行");  
  22.             bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 6));  
  23.             Console.WriteLine(string.Format("6秒超时执行结果,是否超时:{0}", bo));  
  24.              
  25.             timerCallBack(null);  
  26.              
  27.             watch.Stop();  
  28.             timer.Dispose();  
  29.             Console.ReadLine();  
  30.         }  
  31.         staticvoid timerCallBack(object obj)  
  32.         {  
  33.             Console.WriteLine(string.Format("运行时间:{0}秒", watch.Elapsed.TotalSeconds.ToString("F2")));  
  34.         }  
  35.         publicvoid DoSomething()  
  36.         {  
  37.             // 休眠 5秒  
  38.             System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 5));  
  39.         }  
  40.     }  
class Program
    {
        privatestatic Stopwatch watch;
        privatestatic System.Threading.Timer timer;

        [STAThread]
        staticvoid Main(string[] args)
        {
            watch =new Stopwatch();
            Timeout timeout =new Timeout();
            timeout.Do =new Program().DoSomething;
            watch.Start();
            timer =new System.Threading.Timer(timerCallBack, null, 0, 500);
            Console.WriteLine("4秒超时开始执行");
            bool bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 4));
            Console.WriteLine(string.Format("4秒超时执行结果,是否超时:{0}", bo));
            Console.WriteLine("***************************************************");
            
            timeout =new Timeout();
            timeout.Do =new Program().DoSomething;
            Console.WriteLine("6秒超时开始执行");
            bo = timeout.DoWithTimeout(new TimeSpan(0, 0, 0, 6));
            Console.WriteLine(string.Format("6秒超时执行结果,是否超时:{0}", bo));
           
            timerCallBack(null);
           
            watch.Stop();
            timer.Dispose();
            Console.ReadLine();
        }
        staticvoid timerCallBack(object obj)
        {
            Console.WriteLine(string.Format("运行时间:{0}秒", watch.Elapsed.TotalSeconds.ToString("F2")));
        }
        publicvoid DoSomething()
        {
            // 休眠 5秒
            System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 5));
        }
    }

http://blog.csdn.net/educast/article/details/7430932

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值