我有ConcurrentQueue TasksCollection
包含ITask
对象。它不是Task
.Net 框架的类别。
public class TaskRunner:IDisposable
{
private Task _orderTask;
public TaskRunner()
{
TasksCollection = new ConcurrentQueue<ITask>();
}
public void Start()
{
_needToStopOrderTask = false;
_orderTask = Task.Factory.StartNew(() => OrderTaskLoop());
}
public void Stop()
{
lock(_lockObject)
_needToStopOrderTask = true;
}
}
所以,当一些事件发生时,我创建ITask
并添加到ConcurrentQueue
新任务。在线程循环中,我获取每个任务并执行它(同步且一致地执行一些代码。看来,我不能并发它。
private void OrderTaskLoop()
{
try
{
if (TasksCollection.Count == 0)
return;
while (!_needToStopOrderTask)
{
if(TasksCollection.Count>100)//too many tasks
{
//what should i do here?
}
ITask task = null;
var tryTake = TasksCollection.TryDequeue(out task);
///execute
}
}
}
所以,在我的情况下,我认为我可以清除队列并继续工作,因为我的跑步者在实时环境中工作。但是,这种情况可能存在某种模式吗?如果ConcurrentQueue
计数太大该怎么办?
谢谢!