gpt4 book ai didi

c# - 队列到 ConcurrentQueue

转载 作者:行者123 更新时间:2023-12-02 22:12:39 25 4
gpt4 key购买 nike

我在 C# (4.0) 中有一个常规 Queue 对象,我正在使用访问此 Queue 的 BackgroundWorkers。

我使用的代码如下:

   do
{
while (dataQueue.Peek() == null // nothing waiting yet
&& isBeingLoaded == true // and worker 1 still actively adding stuff
)
System.Threading.Thread.Sleep(100);

// otherwise ready to do something:
if (dataQueue.Peek() != null) // because maybe the queue is complete and also empty
{
string companyId = dataQueue.Dequeue();
processLists(companyId);
// use up the stuff here //
} // otherwise nothing was there yet, it will resolve on the next loop.
} while (isBeingLoaded == true // still have stuff coming at us
|| dataQueue.Peek() != null); // still have stuff we haven’t done

但是,我想在处理线程时我应该使用 ConcurrentQueue。我想知道是否有像上面那样在 Do While 循环中使用 ConcurrentQueue 的示例?

我用 TryPeek 尝试的一切都没有用..

有什么想法吗?

最佳答案

您可以使用 BlockingCollection<T> 作为生产者-消费者队列。

我的回答对您的架构做出了一些假设,但您可以按照您认为合适的方式塑造它:

public void Producer(BlockingCollection<string> ids)
{
// assuming this.CompanyRepository exists
foreach (var id in this.CompanyRepository.GetIds())
{
ids.Add(id);
}

ids.CompleteAdding(); // nothing left for our workers
}

public void Consumer(BlockingCollection<string> ids)
{
while (true)
{
string id = null;
try
{
id = ids.Take();
} catch (InvalidOperationException) {
}

if (id == null) break;

processLists(id);
}
}

您可以根据需要启动任意数量的消费者:

var companyIds = new BlockingCollection<string>();
Producer(companyIds);

Action process = () => Consumer(companyIds);

// 2 workers
Parallel.Invoke(process, process);

关于c# - 队列到 ConcurrentQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14991102/

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