Stack Empty Exception

2019-06-18 13:57发布

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?

3条回答
倾城 Initia
2楼-- · 2019-06-18 14:23

If SharedMemory is a Stack, and since you are using Multithreading and if you are on .Net 4 . you should use : ConcurrentStack

Edit

After my first edit and a great comment from Quartermeister this a simpler working solution:

    int item;
    var SharedMemory = new BlockingCollection<int>(new ConcurrentStack<int>());
    // later in the Consume part
    item = SharedMemory.Take(); // this will block until there is an item in the list
    Console.WriteLine(item);
查看更多
Juvenile、少年°
3楼-- · 2019-06-18 14:27

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);
}
查看更多
地球回转人心会变
4楼-- · 2019-06-18 14:28

how is that possible the stack is full & has 16 items??!

In multithreading environment it is very much possible.

Are you using more than one threads in your program? If yes, SharedMemory should be locked before making any change to it.

查看更多
登录 后发表回答