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:
Can someone please explain?
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:
Can someone please explain?
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);
}
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 lock
ed before making any change to it.
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);