gpt4 book ai didi

c# - BlockingCollection 是线程安全的吗?

转载 作者:行者123 更新时间:2023-12-03 12:51:38 25 4
gpt4 key购买 nike

BlockingCollection<int> blockingCollection = new BlockingCollection<int>();
// create and start a producer
Task.Factory.StartNew(() => {
// put items into the collectioon
for (int i = 0; i < 1000; i++)
{
blockingCollection.Add(i);
}
// mark the collection as complete
blockingCollection.CompleteAdding();
});
// create and start a producer
Task.Factory.StartNew(() => {
while (!blockingCollection.IsCompleted)
{
// take an item from the collection
int item = blockingCollection.Take();
// print out the item
Console.WriteLine("Taskid{1} Item {0}", item, Task.CurrentId);
}
});

// create and start a producer
Task.Factory.StartNew(() => {
while (!blockingCollection.IsCompleted) // if the blockingCollection is not completed
{
// take an item from the collection
int item = blockingCollection.Take(); // but in here, all the items have been taken by other thread, this line will wait forever?
// print out the item
Console.WriteLine("Taskid{1} Item {0}", item,Task.CurrentId);
}
});
Console.ReadLine();

关键代码行:

    while (!blockingCollection.IsCompleted)   // if the blockingCollection is not completed
int item = blockingCollection.Take(); // but in here, all the items have been taken by other thread, this line will wait forever?

最佳答案

是的,BlockingCollection<T>线程安全的

为了避免IsCompleted检查您是否可以在 GetConsumingEnumerable() 的帮助下放置相同的逻辑它将等到阻止收集完成:

  // Producer:

Task.Run(() => {
for (int i = 0; i < 1000; i++)
blockingCollection.Add(i);

blockingCollection.CompleteAdding();
});

// Consumers:

Task.Run(() => {
foreach (var item in blockingCollection.GetConsumingEnumerable())
Console.WriteLine("Taskid{1} Item {0}", item, Task.CurrentId);
});

Task.Run(() => {
foreach (var item in blockingCollection.GetConsumingEnumerable())
Console.WriteLine("Taskid{1} Item {0}", item, Task.CurrentId);
});

关于c# - BlockingCollection 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59728872/

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