Empty stack exception

I get the stack exception empty. How is this possible if the stack is not empty (it has 16 elements)?

I got an error click:

Stack empty exception

Can someone explain?

+6
source share
3 answers

You should synchronize access when using something like Stack<T> . The easiest approach is to use lock , which also allows you to use lock for synchronization itself; so the pop will be:

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

and push will be:

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

How is this possible, the stack is full and has 16 elements ?!

In a multi-threaded environment, this is very possible.

Do you use multiple threads in your program? If so, SharedMemory must be lock ed before making any changes to it.

+5
source

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

Edit

After my first edit and a wonderful comment from Quartermeister, this is 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); 
+3
source

All Articles