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";
        }

}

 

posted @ 2020-08-12 17:01  Tozhang  阅读(1188)  评论(0编辑  收藏  举报