队列为空时的生产者-消费者等待吗?

Pet*_*ter 5 c# queue task producer-consumer

我列出了需要按顺序处理的工作项。有时列表将为空,有时将包含一千个项目。一次只能按顺序处理一个。目前,我正在执行以下操作,这些操作对我来说看起来很愚蠢,因为我正在使用Consumer任务中的Thread.Sleep来等待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)
    }

}
Run Code Online (Sandbox Code Playgroud)

忠告不胜感激。

谢谢

Jim*_*hel 6

使用BlockingCollection。它不忙等待。

有关简单示例,请参见/sf/answers/357594121/。或http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=821以获得更多详细信息。