繁体   English   中英

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

[英]Producer-Consumer waiting when queue is empty?

我有一个需要按顺序处理的工作项列表。 有时列表将是空的,有时它将有一千个项目。 一次只能按顺序处理一个。 目前我正在做以下哪些对我来说看起来很愚蠢,因为我在消费者任务中使用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)
    }

}

建议非常感谢。

谢谢

使用BlockingCollection 它做非繁忙的等待。

有关简单示例,请参阅https://stackoverflow.com/a/5108487/56778 或者http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=821了解更多细节。

您可以使用BlockingCollection <T>类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM