超时 函数

很多时候会有这样的情况,比如调用一个第三方的接口程序,但可能配置原因造成调用一个初始化方法直接卡住,等待时间过长,那么最好就是有个超时,5-8秒左右如果没有返回直接返回,感觉这个可能用的地方比较多,所以就随便写了一个方法,方便调用。

 1  public bool TimeOutAction(Action action, int secound)
 2         {
 3             if (action == null || secound > 1)
 4                 return false;
 5 
 6             bool isComplate = false;
 7             bool isTimeOut = false;
 8             int index = 0;
 9             Thread t = new Thread(new ThreadStart(() =>
10             {
11                 while (!isComplate)
12                 {
13                     if (index >= secound)
14                     {
15                         isTimeOut = true;
16                         break;
17                     }
18                     index++;
19                     Thread.Sleep(1000);
20                 }
21 
22             }));
23             Thread t1 = new Thread(new ThreadStart(() =>
24             {
25                 try
26                 {
27                     action();
28                     isComplate = true;
29                 }
30                 catch
31                 {
32                 }
33             }));
34 
35             t.Start();
36             t1.Start();
37 
38             while (!isTimeOut && !isComplate)
39             {
40             }
41             if (isComplate)
42             {
43                 t.Abort();
44                 return false;
45             }
46             if (isTimeOut)
47             {
48                 t1.Abort();
49 
50                 return true;
51             }
52             return false;

53         } 

 

 

posted @ 2012-10-16 17:14  阳光下的风  阅读(207)  评论(0)    收藏  举报