任务超时退出的方法 C#
超出时间方法退出。防止卡住。
方法:
private static bool ImportTaskTimeout(Action method, int hours) { try { var task = Task.Run(() => method()); if (task.Wait(TimeSpan.FromHours(hours))) return task.IsCompleted; else return false; } catch { return false; } }
或者:
static void Main(string[] args) { Task t = Task.Run(() => { Random rnd = new Random(); long sum = 0; int n = 5000000; for (int ctr = 1; ctr <= n; ctr++) { int number = rnd.Next(0, 101); sum += number; Console.WriteLine("ctr: {0:N0}", ctr); } }); TimeSpan ts = TimeSpan.FromMilliseconds(150); if (!t.Wait(ts)) Console.WriteLine("The timeout interval elapsed."); }