Let's suppose we have a class MyQueue defined as below:
public class MyQueue
{
private bool _stop;
private readonly AutoResetEvent _onQueued = new AutoResetEvent(false);
private readonly ConcurrentQueue<int> _queue = new ConcurrentQueue<int>();
public MyQueue()
{
var thread = new Thread(ManageQueue)
{
IsBackground = true
};
thread.Start();
}
public void EnqueueInt(int num)
{
_queue.Enqueue(num);
_onQueued.Set();
}
public void Stop()
{
_stop = true;
_onQueued.Set();
}
private void ManageQueue()
{
while (!_stop)
{
onQueued.WaitOne();
int tempNum;
while(!_stop && _queue.TryDequeue(out tempNum))
{
// Do something with the int
}
}
}
}
So pratically we have a method EnqueueInt
used to queue item inside the data structure and a thread
that cyclically checks if the queue has item to be processed. The signal _onQueued
is used to signal the thread when a new item is inserted or a close operation has been started. My question is: MyQueue has a disposable object (of type AutoResetEvent) and must be disposed when the queue is no longer needed, but, what's the best way to dispose it?
Calling Dispose
after a Close()
operation could be very dangerous because of the Set()
invocation in it and I've no garantee that the Thread has terminated its cycle.
Instead or re-inventing the wheel, you can use System.Collections.Generic.Queue<T>
Also, if you want to manage the lifetime of your queue, I would use a service, so when the service (queue service) is disposed, then you can dispose of it; here is the Microsoft guide on how to create a queue service: https://learn.microsoft.com/en-us/dotnet/core/extensions/queue-service