Assume we have two threads working with a method that execute below:
while(true){ if(Queue.Count() <= 0){ wait(); } object anObject = Queue.Dequeue(); } Now the problem occurs when Queue has one element init, Thread 1 is about to execute Queue.Count line, Thread 2 about is on Queue.Dequeue() and execution priority is on Thread 1.
As this situation occurs, Thread 1 will throw an exception because, Queue.Count() will return 1 and it will try to dequeue an object from an empty queue. How can I handle this? What is the best solution if I want to dequeue safely? Should I use syncronized or lock something?
Best regards, Kemal