I have an application which uses a collection, in this case a queue, from different threads. An object gets enqueued in one thread while another gets dequeued in a different thread.
These actions might occur simultaneously which would resolve in an exception such as argument out of range exception, when the collections counter is being redefined.
I'm looking for a "good looking" and right why to exclude these actions from one another.
what I mean by "good looking" is that I don't want to create my own collection derived from this one which includes a lock(object) mechanism
I don't want to use the brain storming idea I had, which is pretty "ugly"
enqueueOk = false;
while (!enqueueOk)
{
try
{
Qsockets.Enqueue(currentSoc);
enqueueOk = true;
}
catch { }
}
I thought of course using the a lock or a mutex but that would be the case only if I wrap these actions in a procedure which would be called from each thread, and decide either to enqueue or dequeue which would also be long and "ugly"
edit:
because no one seems to see my answer down below
I just used the lock mechanism on the collection itself
lock(Qsockets)
{
Qsockets.Enqueue(currentSoc);
}
Seems like a classic Producer-Consumer scenario. Have you check this nice example?