Является ли BlockingCollection потокобезопасным?C#

Место общения программистов C#
Ответить
Anonymous
 Является ли BlockingCollection потокобезопасным?

Сообщение Anonymous »

BlockingCollection blockingCollection = new BlockingCollection();
// 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 consumer
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 consumer
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?


Подробнее здесь: https://stackoverflow.com/questions/597 ... hread-safe
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»