当队列为空时,生产者-消费者等待

本文关键字:生产者 消费者 等待 队列 | 更新日期: 2023-09-27 18:19:13

我有一个需要按顺序处理的工作项列表。有时这个列表是空的,有时它会有上千个项目。一次只能按顺序处理一个。目前我正在做以下事情,这对我来说看起来很愚蠢,因为我正在使用线程。在消费者任务中休眠,等待100ms,然后检查列表是否为空。这是标准的做法吗?还是我完全错了?

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)
    }
}

建议不胜感激。

谢谢

当队列为空时,生产者-消费者等待

使用BlockingCollection。它只做非忙等待。

参见https://stackoverflow.com/a/5108487/56778的一个简单示例。或http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=821获取更多细节

你可以使用BlockingCollection<类。>