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
}
}
}
If you’re using
ConcurrentQueuefrom .NET 4, it’s best to avoid doing theAutoResetEventhandling yourself entirely. Instead, create aBlockingCollectionto wrap theConcurrentQueueand just use that – it does everything you need. (If you just create aBlockingCollectionusing the parameterless constructor, it’ll create aConcurrentQueuefor you anyway.)EDIT: If you really want to still use
AutoResetEvent, thenWaitOnewill automatically (and atomically) reset the event – that’s the “Auto” part ofAutoResetEvent. Compare this withManualResetEventwhich doesn’t reset the event.