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

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM