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