队列出栈的数据和入栈数据不一样,晕死!

hel_ 2012-03-24 09:33:17
发上代码,功能是把数据入栈,一个线程把数据一个一个弹出栈处理。代码如下,可是在事件里面写代码竟然跟入栈的数据不一样,很多入栈的数据成员变成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);
}
}
...全文
191 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
nonocast 2012-03-25
  • 打赏
  • 举报
回复
锁住push/pop
色拉油 2012-03-25
  • 打赏
  • 举报
回复
如楼上所言,你有的时候还没放进去就取了
hel_ 2012-03-25
  • 打赏
  • 举报
回复
我用了LOCK啊,不过现在查到原因了,多谢二位,这个类是没问题的,是其它类的线程修改了里面的数据。
stonespace 2012-03-24
  • 打赏
  • 举报
回复
多线程吗?如果有多个线程,那么你不能保证一个线程入栈,另一个线程出栈的情况发生,
hel_ 2012-03-24
  • 打赏
  • 举报
回复
急啊,有没有人啊,没搞懂的也帮我顶一顶啊,先谢啦!

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧