C#タイムアウト処理
ネット上でC#タイムアウト処理の方法をたくさん検索しました.次の方法は私がデバッグしたものです.
タイムアウト処理方法を呼び出します.
/// <summary>
///
///
///
/// </summary>
public class TimeoutChecker
{
long _timeout; //
System.Action<Delegate> _proc; //
System.Action<Delegate> _procHandle; //
System.Action<Delegate> _timeoutHandle; //
System.Threading.ManualResetEvent _event = new System.Threading.ManualResetEvent(false);
public TimeoutChecker(System.Action<Delegate> proc, System.Action<Delegate> timeoutHandle)
{
this._proc = proc;
this._timeoutHandle = timeoutHandle;
this._procHandle = delegate
{
//
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
if (this._proc != null)
this._proc(null);
sw.Stop();
//
if (sw.ElapsedMilliseconds < this._timeout && this._event != null)
{
this._event.Set();
}
};
}
public bool Wait(long timeout)
{
this._timeout = timeout;
//
this._procHandle.BeginInvoke(null, null,null);
// false
bool flag = this._event.WaitOne((int)timeout, false);
if (!flag)
{
//
if (this._timeoutHandle != null)
this._timeoutHandle(null);
}
this.Dispose();
return flag;
}
private void Dispose()
{
if(this._event != null)
this._event.Close();
this._event = null;
this._proc = null;
this._procHandle = null;
this._timeoutHandle = null;
}
}
タイムアウト処理方法を呼び出します.
/// <summary>
///
/// </summary>
/// <param name="device"> </param>
/// <param name="image"> , </param>
/// <returns>image , </returns>
public bool isCameraWork(Camera device, NImage image)
{
try
{
device.StartCapturing();
TimeoutChecker timeout = new TimeoutChecker(
delegate
{
try
{
image = device.GetCurrentFrame();
}
catch
{
image = null;
nlView.Image = null;
}
},
delegate
{
Console.WriteLine(device.ToString() + " ");
});
if (timeout.Wait(1000))
Console.WriteLine(device.ToString() + " ");
}
catch (Exception e)
{
image = null;
Console.WriteLine(device.ToString() + e.Message);
}
device.StopCapturing();
if (image != null)
return true;
else
return false;
}