本文介绍了堆栈空异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个堆栈为空的异常.如果堆栈不为空(有16个项目)怎么办?

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<T>之类的东西,您必须同步访问.最简单的方法是使用lock,然后让您将lock用于同步本身.所以流行会是:

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

并推将是:

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

这篇关于堆栈空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 21:07