NOTE:
我对我的问题进行了彻底的修改。您可以通过更改历史记录查看原始问题。
我需要一个“强大的”队列,它提供以下功能:
- 我对一组对象有一定的范围。这意味着Group A, Group B, ...将有自己的队列
- 我正在组范围内的线程中填充队列Thread A(制作人)
- 我正在读取组范围线程中的队列Thread B(消费者)
所以我会有以下场景:
- 队列中现在和将来都不会有项目(因为作业是用空的“目标组”调用的):Thread B应该跳出循环
- 目前队列中没有项目,因为Thread A正在处理要排队的项目:Thread B应该等待
- 队列中有项目:Thread B应该能够使项目出队并处理
- 队列中没有项目,因为Thread A没有更多项目要排队:Thread B应该跳出循环
现在我想出了以下实现:
public class MightyQueue<T>
where T : class
{
private readonly Queue<T> _queue = new Queue<T>();
private bool? _runable;
private volatile bool _completed;
public bool Runable
{
get
{
while (!this._runable.HasValue)
{
Thread.Sleep(100);
}
return this._runable ?? false;
}
set
{
this._runable = value;
}
}
public void Enqueue(T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
this._queue.Enqueue(item);
}
public void CompleteAdding()
{
this._completed = true;
}
public bool TryDequeue(out T item)
{
if (!this.Runable)
{
item = null;
return false;
}
while (this._queue.Count == 0)
{
if (this._completed)
{
item = null;
return false;
}
Thread.Sleep(100);
}
item = this._queue.Dequeue();
return true;
}
}
然后将使用
Producer
if (anythingToWorkOn)
{
myFooMightyQueueInstance.Runable = false;
}
else
{
myFooMightyQueueInstance.Runable = true;
while (condition)
{
myFooMightyQueueInstance.Enqueue(item);
}
myFooMightyQueueInstance.CompleteAdding();
}
Consumer
if (!myFooMightyQueueInstance.Runable)
{
return;
}
T item;
while (myFooMightyQueueInstance.TryDequeue(out item))
{
//work with item
}
但我相信,这种方法是错误的,因为我正在使用一些Thread.Sleep()
-那里的东西(不能有一些 waitHandle 或其他东西吗?)...我也不是关于算法本身...
有人可以帮我吗?
如果您有 .Net 4.0,请使用BlockingCollection。它通过以下方式为您处理所有混乱,包括最后一点CompleteAdding method.
如果您有较早的 .Net,请升级(即,我懒得解释如何实现已经为您完成的东西。)
EDIT:我认为你的问题根本不值得线程处理。只需提前创建所有电子邮件,然后睡觉直到指定时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)