超出时间方法退出。防止卡住。
方法:


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

 

相关文章:

  • 2022-02-09
  • 2021-06-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2022-12-23
相关资源
相似解决方案