C# 指定方法的超时时间,超出时限后,直接抛出异常

        public static void Invoke(Action method, int milliseconds)
        {
            Thread thdToKill = null;

            Action invokemethod = new Action(() =>
            {
                thdToKill = Thread.CurrentThread;
                method();
            });

            IAsyncResult ar = invokemethod.BeginInvoke(null, null);
            if (!ar.AsyncWaitHandle.WaitOne(milliseconds))
            {
                thdToKill.Abort();
                throw new Exception(string.Format("操作失败,原因:超时 {0}毫秒", milliseconds));
            }

            invokemethod.EndInvoke(ar);
        }

 

posted @ 2015-11-13 12:02  逍遥子k  阅读(1562)  评论(0编辑  收藏  举报