延长WaitHandle.WaitOne超时的时间

时间:2015-05-21 14:20:49

标签: .net multithreading

框架中是否有现有类型,这将允许我做类似于下面示例的操作?基本上,我希望能够增加超时的持续时间。

MagicWaitHandle waitHandle;

Main()
{
 var fooBar = new FooBar();
 fooBar.OnEvent += HandleEvent;
 fooBar.Start(); // starts new thread

 waitHandle.WaitOne(new TimeSpan(0,1,0)); // suspend
}

HandleEvent(Foo f)
{
 if(f.SomeCondition) waitHandle.ExtendWaitPeriodBy(new TimeSpan(0,1,0)); // extend
 else if(f.OtherCondition) waitHandle.Set(); // signal
}

1 个答案:

答案 0 :(得分:1)

框架中没有任何内容可以提供您所要求的内容。不过,你可以为WaitHandle编写一个装饰器并改为使用它。

以下伪代码可以帮助您开始实施。

public class MagicWaitHandle : WaitHandle
{
    private readonly WaitHandle inner;
    public MagicWaitHandle(WaitHandle inner)
    {
        if (inner == null) throw new ArgumentNullException("inner");
        this.inner = inner;
        this.SafeWaitHandle = inner.SafeWaitHandle;
    }

    public override bool WaitOne(TimeSpan timeout)
    {
        if (!base.WaitOne(timeout) )
        {
            if (<needs Apply Extended Timeout>)
            {
                return base.WaitOne(extendedTimeSpan);
            }
        }
        return false;
    }

    public override bool WaitOne(TimeSpan timeout, bool exitContext)
    {
        if (!base.WaitOne(timeout, exitContext))
        { 
            if (<needs Apply Extended Timeout>)
            {
                return base.WaitOne(extendedTimeSpan, exitContext);
            }
        }
        return false;
    }

    public void ExtendWaitPeriodBy(TimeSpan timeSpan)
    {
        //...
    }
}

确保在实施时考虑线程安全性。完成MagicWaitHandle后,您可以将其用作

MagicWaitHandle magicHandle = new MagicWaitHandle(new ManualResetEvent(false));
...
magicHandle.WaitOne(timeout);

其他代码

magicHandle.ExtendWaitPeriodBy(extensionTimeout);