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