限制数据库连接时间

来源:互联网 发布:java配置文件是什么 编辑:程序博客网 时间:2024/04/30 19:42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data;
namespace CommonTest.Business
{
    /// 要执行的方法的委托类
    public delegate object MethodHandler();
    public class Timeout
    {
        ///
        /// 手动信号机
        ///
        private ManualResetEvent signalMachine;
        ///
        /// 是否超时
        ///
        private bool isTimeout;
        ///
        /// 需要执行的方法的委托
        ///
        public MethodHandler Method;
        //如果方法有参数,那么应该将参数做成这个类的属性出现




        public Timeout()
        {
            //信号机的初始状态的停止状态
            this.signalMachine = new ManualResetEvent(true);
        }
        ///
        ///执行方法,返回是否超时
        ///
        ///返回:是否超时
        public bool ExecuteMethodWithTimeout(TimeSpan timeSpan)
        {
            //如果没有方法被注册
            if (this.Method == null)
            {
                //那么直接返回未超时
                return false;
            }
            //如果有方法被注册
            //重置信号机
            this.signalMachine.Reset();
            //先将状态设定为超时状态
            this.isTimeout = true;
            //然后开始异步调用方法来确定是否真的超时(如果委托类有参数,那么此处应该将参数传递进来)
            this.Method.BeginInvoke(DoAsyncCallBack, null);
            //用手动信号机等待
            if (!this.signalMachine.WaitOne(timeSpan, false))
            {
                //如果的确超时,那么设置超时状态为真
                this.isTimeout = true;
            }
            //返回超时状态
            return this.isTimeout;
        }
        ///
        ///回调函数
        ///
        ///
        private void DoAsyncCallBack(IAsyncResult result)
        {
            try
            {
                this.Method.EndInvoke(result);
                //如果能顺利的执行到这里,证明没有超时
                this.isTimeout = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //如果执行到这里,证明要么出错了,要么超时了。
                this.isTimeout = true;
            }
            finally
            {
                //释放信号
                this.signalMachine.Set();
            }
        }
       
    }
}
原创粉丝点击