Take a look at the code below. Assume that this is the ENTIRE class. I have not omitted ANY code. This is literally all it does.
If I instantiate this class in my main program loop and call myExample.Add(whatever) from time to time, do I need to worry about any problems caused by not locking around Dequeue() and Enqueue()?
public class Example<T>
{
private Queue<T> q = new Queue<T>();
public Example()
{
new Thread(() =>
{
while (true)
{
if (this.q.Count > 0)
{
var item = this.q.Dequeue();
}
Thread.Sleep(1);
}
}).Start();
}
public void Add(T val)
{
this.q.Enqueue(val);
}
}
What happens if this.q.Enqueue(val) is called at the same time as this.q.Dequeue()?