Search code examples
c#autoreseteventconcurrent-collections

AutoResetEvent process?


private ConcurrentQueue<Data> _queue = new ConcurrentQueue<Data>();
private AutoResetEvent _queueNotifier = new AutoResetEvent(false);

public void MoreData(Data example)
{
    _queue.Enqueue(example);
    _queueNotifier.Set();
}

private void _SimpleThreadWorker()
{
    while (_socket.Connected)
    {
        _queueNotifier.WaitOne();
        Data data;
        if (_queue.TryDequeue(out data))
        {
            //handle the data
        }
    }
}

Do I have to set the event to false once I have it Dequeue or the event goes back to false on it's own when it hits back _queueNotifier.WaitOne() or how it works exactly ?

Should I use a inner while like the below example instead or both ways are just fine/equal ?

while (_socket.Connected)
{
    _queueNotifier.WaitOne();
    while (!_queue.IsEmpty)
    {
        Data data;
        if (_queue.TryDequeue(out data))
        {
            //handle the data
        }
    }
}

Solution

  • If you're using ConcurrentQueue from .NET 4, it's best to avoid doing the AutoResetEvent handling yourself entirely. Instead, create a BlockingCollection to wrap the ConcurrentQueue and just use that - it does everything you need. (If you just create a BlockingCollection using the parameterless constructor, it'll create a ConcurrentQueue for you anyway.)

    EDIT: If you really want to still use AutoResetEvent, then WaitOne will automatically (and atomically) reset the event - that's the "Auto" part of AutoResetEvent. Compare this with ManualResetEvent which doesn't reset the event.