我用一个线程问题回答了一个帖子,这个问题被否决了很多次,但现在它让我重新猜中了一个已经运行多年的现成解决方案。如果我有一些工作需要经常做,但并不总是像处理队列中的元素那样。是让线程在不工作时休眠,还是在每次需要处理元素时启动任务。基于对线程生命周期(即应用程序运行的长度)的研究,创建一个新线程似乎是更好的选择。任务解决方案比另一个好吗?如果你有另一个版本,你认为比这两个更好的问题,请随时提交。
class DoSomething
{
public void Enqueue(object item)
{
Task.Run(() => ProcessItem(item));
}
public void ProcessItem(object item)
{
//Do some work here that needs to be async from submission
}
}
class DoSomething2
{
public DoSomething2()
{
_t = new Thread(ProcessItem) { IsBackground = true };
_t.Start();
}
private Thread _t;
private ConcurrentQueue<object> _queue = new ConcurrentQueue <object>();
public void Enqueue(object item)
{
_queue.Enqueue(item);
}
public void ProcessItem(object item)
{
while (true)
{
while (_queue.Count > 0)
{
//Dequeue here and do some work here that needs to be async from submission
}
System.Threading.Thread.Sleep(100);
}
}
}
编辑1。因为有人问我,我想提供更多的信息。这个类是我为一组分布式服务集中事件而创建的日志类的模型。有些有许多事件,数量约为数百万,有些一天中可能有几百个事件。有没有一个解决方案对两者都是最优的。我对任务的关注是,创建数百万个任务对象的开销将超过火和遗忘的好处。