日期:2014-05-18  浏览次数:20785 次

队列出栈的数据和入栈数据不一样,晕死!
发上代码,功能是把数据入栈,一个线程把数据一个一个弹出栈处理。代码如下,可是在事件里面写代码竟然跟入栈的数据不一样,很多入栈的数据成员变成NULL了,高手帮帮忙!

  public class QueuedDataProcessor<T> where T : class
  {
  private bool stop = false;
  private Queue<T> internalQueue;
  private Thread processingThread;

  public QueuedDataProcessor() {
  internalQueue = new Queue<T>();

  this.processingThread = new Thread(new ThreadStart(CallingThread));
  this.processingThread.IsBackground = true;
  this.processingThread.Start();
  }

  public void Enqueue(T data) {
  if (stop == true)
  throw new Exception("停止的对象不能再使用。");

  lock (internalQueue) {
  internalQueue.Enqueue(data);
  //T test = internalQueue.Dequeue();
   
  }
  }

  public int LeftCount {
  get { return internalQueue.Count; }
  }

  public void Stop() {
  if (!stop) {
  stop = true;
  processingThread.Join();
  }
  }

  private void CallingThread() {
  while (!stop) {
  //先粗略判断,优化速度
  if (internalQueue.Count == 0) {
  Thread.Sleep(100);
  continue;
  }

  lock (internalQueue) {
  if (internalQueue.Count > 0) {
  T data = internalQueue.Dequeue();
  OnProcessDataEventHandler(data);
  }
  }
  }
  }

  public delegate void ProcessDataEventHandler<U>(object sender, U data);
  public event ProcessDataEventHandler<T> ProcessData;
   
  protected void OnProcessDataEventHandler(T data) {
  if (ProcessData != null)
  ProcessData.Invoke(this, data);
  }
  }


------解决方案--------------------
多线程吗?如果有多个线程,那么你不能保证一个线程入栈,另一个线程出栈的情况发生,
------解决方案--------------------
如楼上所言,你有的时候还没放进去就取了
------解决方案--------------------
锁住push/pop