WaitUtil.cs
1.9 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
using log4net;
using System;
using System.Reflection;
using System.Threading;
namespace Common
{
public class WaitUtil
{
public delegate bool IsOk();
static readonly LogBean logBean = new LogBean(MethodBase.GetCurrentMethod()?.DeclaringType.FullName);
/// <summary>
/// 使用异步委托检测超时,防止isOk方法不返回结果导致卡死的问题
/// </summary>
/// <param name="waitName"></param>
/// <param name="timeout"></param>
/// <param name="isOk"></param>
public static bool Wait(int timeout, IsOk isOk, string waitName = "")
{
DateTime startTime = System.DateTime.Now;
TimeSpan timoutSpan = TimeSpan.FromMilliseconds(timeout);
TimeSpan waitSpan = TimeSpan.FromMilliseconds(0);
int sleepTime = 10;
while (true)
{
TimeSpan remainTimes = timoutSpan.Subtract(waitSpan);
if (remainTimes.TotalMilliseconds < 0)
{
//已经超时
throw new TimeoutException(waitName + "超时");
}
try
{
IAsyncResult re = isOk.BeginInvoke(null, null);
var waitResult = re.AsyncWaitHandle.WaitOne(remainTimes);
if (waitResult)
{
bool okResult = isOk.EndInvoke(re);
if (okResult)
{
return true;
}
}
}
catch (Exception ex)
{
LogUtil.Error("同步等待出现异常",ex,logBean);
}
Thread.Sleep(sleepTime);
waitSpan = System.DateTime.Now.Subtract(startTime);
}
}
}
}