WaitUtil.cs
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace URSoldering.Common
{
public class WaitUtil
{
public delegate bool IsOk();
/// <summary>
/// 同步等待,如果等到结果返回true, 超时或出现异常返回false
/// </summary>
/// <param name="timeout">超时时间(毫秒)</param>
/// <param name="isOk">等待</param>
/// <returns></returns>
public static bool Wait(int timeout, IsOk isOk)
{
try{
Wait("", timeout, isOk);
return true;
}
catch(TimeoutException te)
{
return false;
}catch(Exception e)
{
LogUtil.error("同步等待出现异常:"+ e.Message);
return false;
}
}
/// <summary>
/// 同步等待,如果等到结果正常返回, 超时抛出TimeoutException
/// </summary>
/// <param name="waitName">等待的名称,超时的时候TimeoutException的消息为:xxx超时</param>
/// <param name="timeout"></param>
/// <param name="isOk"></param>
public static void Wait(string waitName, int timeout, IsOk isOk)
{
int waitTime = 0;
int sleepTime = 10;
while (true)
{
try
{
bool result = isOk();
if (result)
{
return;
}
}
catch (Exception ex)
{
LogUtil.error("同步等待出现异常:" + ex.Message);
}
if (waitTime > timeout)
{
throw new TimeoutException(waitName + "超时");
}
Thread.Sleep(sleepTime);
waitTime = waitTime + sleepTime;
}
}
}
}