本文介绍了的AutoResetEvent设置后立即复位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下方式:

private AutoResetEvent signal = new AutoResetEvent(false);

private void Work()
{
    while (true)
    {
        Thread.Sleep(5000);
        signal.Set();
        //has a waiting thread definitely been signaled by now?
        signal.Reset();
    }
}

public void WaitForNextEvent()
{
    signal.WaitOne();
}



这个模式的目的是允许外部消费者等待某一事件(例如: - 消息到达)。 WaitForNextEvent 不是从类中调用。

要放弃,应该是熟悉的一个例子,考虑的System.Diagnostics.Process 。它暴露了一个已退出事件,但它也暴露了一个 WaitForExit 方法,它允许调用方同步等待,直到进程退出。这就是我想在这里实现。

To give an example that should be familiar, consider System.Diagnostics.Process. It exposes an Exited event, but it also exposes a WaitForExit method, which allows the caller to wait synchronously until the process exits. this is what I am trying to achieve here.

我需要的原因 signal.Reset()是,如果一个线程调用 WaitForNextEvent signal.Set()已经被调用(或换句话说,如果。设置时没有线程在等待被称为),它立即返回,因为该事件已经被预先发出信号。

The reason I need signal.Reset() is that if a thread calls WaitForNextEvent after signal.Set() has already been called (or in other words, if .Set was called when no threads were waiting), it returns immediately, as the event has already been previously signaled.


  • 它是保证一个线程调用了 WaitForNextEvent() signal.Reset()调用之前发出信号?如果没有,什么是实施 WaitFor的方法其他解决办法?

  • Is it guaranteed that a thread calling WaitForNextEvent() will be signaled before signal.Reset() is called? If not, what are other solutions for implementing a WaitFor method?

推荐答案

而不是使用的AutoResetEvent 的ManualResetEvent ,使用这样的:

Instead of using AutoResetEvent or ManualResetEvent, use this:

public sealed class Signaller
{
    public void PulseAll()
    {
        lock (_lock)
        {
            Monitor.PulseAll(_lock);
        }
    }

    public void Pulse()
    {
        lock (_lock)
        {
            Monitor.Pulse(_lock);
        }
    }

    public void Wait()
    {
        Wait(Timeout.Infinite);
    }

    public bool Wait(int timeoutMilliseconds)
    {
        lock (_lock)
        {
            return Monitor.Wait(_lock, timeoutMilliseconds);
        }
    }

    private readonly object _lock = new object();
}



然后改变,像这样的代码:

Then change your code like so:

private Signaller signal = new Signaller();

private void Work()
{
    while (true)
    {
        Thread.Sleep(5000);
        signal.Pulse(); // Or signal.PulseAll() to signal ALL waiting threads.
    }
}

public void WaitForNextEvent()
{
    signal.Wait();
}

这篇关于的AutoResetEvent设置后立即复位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 05:58