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

参考:https://www.bbsmax.com/A/A2dmN7m4ze/     

https://www.cnblogs.com/leicao/p/5251090.html 

https://www.cnblogs.com/mmnyjq/p/5482705.html  

https://www.cnblogs.com/qwqwQAQ/p/8484426.html

思路:使用委托 ,进程阻塞

//声明委托
        private delegate string GetIdDelegate(string name);

        public bool IsHaveId(string name)
        {
            bool result1=false;
            DAL _DAL;
            GetIdDelegate geId = _DAL.GetId;
            var result = geId.BeginInvoke(name, null, null);
            if (result.AsyncWaitHandle.WaitOne(5 * 1000))
            {
                var id = geId.EndInvoke(result);
                if (id == "1")
                {
                    result1 = true;
                }
            }
            else
            {
                //threadToKill.Abort();
                result1 = false;
                throw new TimeoutException("啦!!");
            }
            return result1;
        }
 public abstract class DAL
    {
    public string GetId(string name)
        {
            Thread.Sleep(5000);
            return "1";
        }

}

 

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

上一篇:《逆向工程核心原理》——通过调试方式hook Api


下一篇:PHP SQL 注入攻击的技术实现以及预防办法