Stack Empty Exception

Ibrahim Ahmed picture Ibrahim Ahmed · Jan 2, 2013 · Viewed 15.3k times · Source

I am getting a stack empty exception. How is that possible if the stack is not empty (it has 16 items)?

I got a snap shot of the error:

Stack Empty Exception

Can someone please explain?

Answer

Marc Gravell picture Marc Gravell · Jan 2, 2013

You must synchronize access when using something like Stack<T>. The simplest approach is to use lock, which then also let's you use the lock for the synchronization itself; so pop would be:

int item;
lock (SharedMemory)
{
    while (SharedMemory.Count == 0)
    {
        Monitor.Wait(SharedMemory);
    }
    item = SharedMemory.Pop();
}
Console.WriteLine(item);

and push would be:

lock (SharedMemory)
{
    SharedMemory.Push(item);
    Monitor.PulseAll(SharedMemory);
}