Beyond Programming Beyond Programming - 1 month ago 21
C# Question

Stack Empty Exception

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

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);
}