【发布时间】:2011-12-31 17:40:29
【问题描述】:
我有一个需要按顺序处理的工作项列表。有时列表会是空的,有时会有一千个项目。一次只能按顺序处理一个。目前我正在执行以下操作,这在我看来很愚蠢,因为我在消费者任务中使用 Thread.Sleep 等待 100 毫秒,然后再检查列表是否为空。这是标准的做法还是我完全错了。
public class WorkItem
{
}
public class WorkerClass
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = new CancellationToken();
List<WorkItem> listOfWorkItems = new List<WorkItem>();
public void start()
{
Task producerTask = new Task(() => producerMethod(ct), ct);
Task consumerTask = new Task(() => consumerMethod(ct), ct);
producerTask.Start();
consumerTask.Start();
}
public void producerMethod(CancellationToken _ct)
{
while (!_ct.IsCancellationRequested)
{
//Sleep random amount of time
Random r = new Random();
Thread.Sleep(r.Next(100, 1000));
WorkItem w = new WorkItem();
listOfWorkItems.Add(w);
}
}
public void consumerMethod(CancellationToken _ct)
{
while (!_ct.IsCancellationRequested)
{
if (listOfWorkItems.Count == 0)
{
//Sleep small small amount of time to avoid continuously polling this if statement
Thread.Sleep(100);
continue;
}
//Process first item
doWorkOnWorkItem(listOfWorkItems[0]);
//Remove from list
listOfWorkItems.RemoveAt(0);
}
}
public void doWorkOnWorkItem(WorkItem w)
{
// Do work here - synchronous to execute in order (10ms to 5min execution time)
}
}
建议非常感谢。
谢谢
【问题讨论】:
标签: c# queue task producer-consumer