J
Jeronimo Bertran
I have a multithreaded application that manipulates a Queue:
protected Queue outputQueue;
when I add elements to the queue I use a critical section
private void Add(OutputRecord record)
{
lock(outputQueue)
{
// Add the element
outputQueue.Enqueue(record);
}
}
when I remove an element from the queue I do something similar:
private OuputRecord Remove()
{
OutputRecord record;
lock (outputQueue)
{
// Remove the element
record = (OutputRecord) outputQueue.Dequeue();
}
return record;
}
Now I want to be able to have a process that adds an element and then
waits until the queue is empty. What is the best way to do this? I
thought of creating an additional object called emptyOutputQueue and
creating a WaitAdd function:
private bool WaitAdd(OutputRecord record)
{
lock(emptyOutputQueue)
{
Add(record);
if (! Monitor.Wait(emptyOutputQueue, 20000))
return false;
}
return true;
}
and changing the Remove function to be something like this
private OuputRecord Remove()
{
OutputRecord record;
lock (outputQueue)
{
// Remove the element
record = (OutputRecord) outputQueue.Dequeue();
if (outputQueue.Count == 0)
{
lock (emptyOutputQueue)
{
Monitor.PulseAll(emptyOutputQueue);
}
}
}
}
But I am not sure that the WaitAdd function will actually wait if the
queue is not empty. Any suggestions of what is the best solution?
Thanks
Jeronimo
protected Queue outputQueue;
when I add elements to the queue I use a critical section
private void Add(OutputRecord record)
{
lock(outputQueue)
{
// Add the element
outputQueue.Enqueue(record);
}
}
when I remove an element from the queue I do something similar:
private OuputRecord Remove()
{
OutputRecord record;
lock (outputQueue)
{
// Remove the element
record = (OutputRecord) outputQueue.Dequeue();
}
return record;
}
Now I want to be able to have a process that adds an element and then
waits until the queue is empty. What is the best way to do this? I
thought of creating an additional object called emptyOutputQueue and
creating a WaitAdd function:
private bool WaitAdd(OutputRecord record)
{
lock(emptyOutputQueue)
{
Add(record);
if (! Monitor.Wait(emptyOutputQueue, 20000))
return false;
}
return true;
}
and changing the Remove function to be something like this
private OuputRecord Remove()
{
OutputRecord record;
lock (outputQueue)
{
// Remove the element
record = (OutputRecord) outputQueue.Dequeue();
if (outputQueue.Count == 0)
{
lock (emptyOutputQueue)
{
Monitor.PulseAll(emptyOutputQueue);
}
}
}
}
But I am not sure that the WaitAdd function will actually wait if the
queue is not empty. Any suggestions of what is the best solution?
Thanks
Jeronimo