gpt4 book ai didi

c# - 有什么方法可以立即触发 WaitOne() 超时?

转载 作者:可可西里 更新时间:2023-11-01 13:51:08 29 4
gpt4 key购买 nike

在 Microsoft .NET 中,方法 WaitOne()

public virtual bool WaitOne(
TimeSpan timeout
)

如果当前实例收到信号,将返回true;否则,false

我的问题是,有没有办法让它在超时点还没到的时候返回false
或者
换句话说,有没有一种方法可以在WaitOne()上立即触发超时,即使真正的超时点还没有到来?

更新:

该项目基于.NET 3.5,所以ManualResetEventSlim可能不起作用(在 .NET 4 中引入)。无论如何谢谢@ani

最佳答案

你不能取消 WaitOne 但你可以包装它:

public bool Wait(WaitHandle yourEvent, WaitHandle cancelEvent, TimeSpan timeOut)
{
WaitHandle[] handles = new WaitHandle[] { yourEvent, cancelEvent };

// WaitAny returns the index of the event that got the signal
var waitResult = WaitHandle.WaitAny(handles, timeOut);

if(waitResult == 1)
{
return false; // cancel!
}

if(waitResult == WaitHandle.WaitTimeout)
{
return false; // timeout
}

return true;
}

只需传递您要等待的句柄和取消等待和超时的句柄即可。

额外

作为一个扩展方法,它可以以类似于 WaitOne 的方式被调用:

public static bool Wait(this WaitHandle yourEvent, WaitHandle cancelEvent, TimeSpan timeOut)
{
WaitHandle[] handles = new WaitHandle[] { yourEvent, cancelEvent };

// WaitAny returns the index of the event that got the signal
var waitResult = WaitHandle.WaitAny(handles, timeOut);

if(waitResult == 1)
{
return false; // cancel!
}

if(waitResult == WaitHandle.WaitTimeout)
{
return false; // timeout
}

return true;
}

关于c# - 有什么方法可以立即触发 WaitOne() 超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678428/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com