gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:33:48 26 4
gpt4 key购买 nike

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

}

非常感谢您的建议。

谢谢

最佳答案

使用BlockingCollection .它不忙等待。

参见 https://stackoverflow.com/a/5108487/56778举个简单的例子。或者 http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=821了解更多详情。

关于c# - 生产者消费者在队列为空时等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com