C#实现函数超出指定时间,自动退出

代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading;
 5 
 6 namespace HelloWorld
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Console.WriteLine("Begin:" + DateTime.Now);
13             bool ret = Process(string.Empty, 100);
14             Console.WriteLine("Result={0}", ret);
15             Console.WriteLine("End:" + DateTime.Now);
16             Console.WriteLine("Press any key to exit...");
17             Console.ReadKey(true);
18         }
19         private static bool Process(string param, int timeout)
20         {
21             bool ret = false;
22             new System.Threading.Tasks.TaskFactory().StartNew(() => {
23                 ret = LongTimeFunc();
24             }).Wait(timeout);
25             Console.WriteLine("退出函数");
26             return ret;
27         }
28 
29         private static bool LongTimeFunc()
30         {
31             System.Threading.Thread.Sleep(50000000);
32             return true;
33         }
34     }
35 }

 

上一篇:4类型转换


下一篇:LeetCode第九题--回文数