C#で動作タイムアウト検出を実行
3538 ワード
public delegate void DoHandler();
public class TimeoutLimit
{
private readonly ManualResetEvent _mTimeoutObject;
private bool _timeout;
public DoHandler Do;
public TimeoutLimit()
{
_mTimeoutObject = new ManualResetEvent(true);
}
public bool DoWithTimeout(TimeSpan timeSpan)
{
if (Do == null)
{
return false;
}
_mTimeoutObject.Reset();
_timeout = true;
Do.BeginInvoke(DoAsyncCallBack, null);
if (!_mTimeoutObject.WaitOne(timeSpan, false))
{
_timeout = true;
}
return _timeout;
}
private void DoAsyncCallBack(IAsyncResult result)
{
try
{
Do.EndInvoke(result);
_timeout = false;
}
catch (Exception ex)
{
_timeout = true;
}
finally
{
_mTimeoutObject.Set();
}
}
}
使用例
//TimeoutLimit timeout = new TimeoutLimit { Do = Your Func };
//bool bo = timeout.TimeoutLimit(new TimeSpan(0, 0, 0, 1));
//if (bo) {Your Code}