AutoResetEvent
如果花费太多时间,我正在尝试使用以进行操作或离开。
这是我正在运行的代码:
TimeoutAction action = new TimeoutAction(1000, OuvrirDrawer);
action.Start();
这是我的TimeoutAction
课:
public class TimeoutAction
{
private Thread ActionThread { get; set; }
private Thread TimeoutThread { get; set; }
private AutoResetEvent ThreadSynchronizer { get; set; }
private bool _success;
private bool _timout;
public TimeoutAction(int waitLimit, Action action)
{
ThreadSynchronizer = new AutoResetEvent(false);
ActionThread = new Thread(new ThreadStart(delegate
{
action.Invoke();
if (_timout) return;
_timout = false;
_success = true;
ThreadSynchronizer.Set();
}));
TimeoutThread = new Thread(new ThreadStart(delegate
{
Thread.Sleep(waitLimit);
if (_success) return;
_timout = true;
_success = false;
ThreadSynchronizer.Set();
}));
}
/// <summary>
/// If the action takes longer than the wait limit, this will throw a TimeoutException
/// </summary>
public void Start()
{
ActionThread.Start();
TimeoutThread.Start();
ThreadSynchronizer.WaitOne();
if (_success)
{
// TODO when action has completed
}
ThreadSynchronizer.Close();
}
}
我预计它最多需要 1000 毫秒,因为它将在TimeoutAction
1000 毫秒后发送信号。因此,即使该方法OuvrirDrawer
需要 5 秒,我也应该在大约 1000 毫秒后到达我的 TODO 行。好吧,你猜怎么着,不是。
我的方法OuvrirDrawer
是尝试打开我的钱箱,但是当它没有连接到我的电脑时,它就崩溃了。我放了一个空的按钮,但是当它试图打开它时,它需要一段时间(5 秒)。
使用上面的代码,我想在 1 秒时超时,我不想等待 5 秒才能看到我的现金抽屉没有连接。一秒钟就足够了。