BlockingCollection<T>.GetConsumingEnumerable Метод

Определение

Предоставляет получающий интерфейс IEnumerable<T> для элементов коллекции.

Перегрузки

GetConsumingEnumerable(CancellationToken)

Предоставляет получающий интерфейс IEnumerable<T> для элементов коллекции.

GetConsumingEnumerable()

Предоставляет получающий интерфейс IEnumerable<T> для элементов коллекции.

GetConsumingEnumerable(CancellationToken)

Исходный код:
BlockingCollection.cs
Исходный код:
BlockingCollection.cs
Исходный код:
BlockingCollection.cs

Предоставляет получающий интерфейс IEnumerable<T> для элементов коллекции.

public:
 System::Collections::Generic::IEnumerable<T> ^ GetConsumingEnumerable(System::Threading::CancellationToken cancellationToken);
public System.Collections.Generic.IEnumerable<T> GetConsumingEnumerable (System.Threading.CancellationToken cancellationToken);
member this.GetConsumingEnumerable : System.Threading.CancellationToken -> seq<'T>
Public Function GetConsumingEnumerable (cancellationToken As CancellationToken) As IEnumerable(Of T)
Public Iterator Function GetConsumingEnumerable (cancellationToken As CancellationToken) As IEnumerable(Of T)

Параметры

cancellationToken
CancellationToken

Маркер отмены, который следует контролировать.

Возвращаемое значение

Интерфейс IEnumerable<T>, удаляющий и возвращающий элементы из коллекции.

Исключения

Был удален BlockingCollection<T> или объект CancellationTokenSource, создавший cancellationToken.

Комментарии

Этот метод позволяет клиентскому коду удалять элементы из коллекции с помощью цикла foreach (For Each в Visual Basic) или Parallel.ForEach запроса PLINQ. Перечислитель будет продолжать предоставлять элементы (если таковые существуют), пока не IsCompleted вернет значение true, а если IsCompleted имеет значение false, цикл блокируется до тех пор, пока элемент не станет доступным или пока не CancellationToken будет отменен.

См. также раздел

Применяется к

GetConsumingEnumerable()

Исходный код:
BlockingCollection.cs
Исходный код:
BlockingCollection.cs
Исходный код:
BlockingCollection.cs

Предоставляет получающий интерфейс IEnumerable<T> для элементов коллекции.

public:
 System::Collections::Generic::IEnumerable<T> ^ GetConsumingEnumerable();
public System.Collections.Generic.IEnumerable<T> GetConsumingEnumerable ();
member this.GetConsumingEnumerable : unit -> seq<'T>
Public Function GetConsumingEnumerable () As IEnumerable(Of T)

Возвращаемое значение

Интерфейс IEnumerable<T>, удаляющий и возвращающий элементы из коллекции.

Исключения

Объект BlockingCollection<T> удален.

Примеры

В следующем примере показано, как использовать GetConsumingEnumerable метод :

class ConsumingEnumerableDemo
{
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.CompleteAdding()
    //      BlockingCollection<T>.GetConsumingEnumerable()
    public static async Task BC_GetConsumingEnumerable()
    {
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {
            // Kick off a producer task
            var producerTask = Task.Run(async () =>
            {
                for (int i = 0; i < 10; i++)
                {
                    bc.Add(i);
                    Console.WriteLine($"Producing: {i}");

                    await Task.Delay(100); // sleep 100 ms between adds
                }

                // Need to do this to keep foreach below from hanging
                bc.CompleteAdding();
            });

            // Now consume the blocking collection with foreach.
            // Use bc.GetConsumingEnumerable() instead of just bc because the
            // former will block waiting for completion and the latter will
            // simply take a snapshot of the current state of the underlying collection.
            foreach (var item in bc.GetConsumingEnumerable())
            {
                Console.WriteLine($"Consuming: {item}");
            }
            await producerTask; // Allow task to complete cleanup
        }
    }
}
module ConsumingEnumerableDemo =
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.CompleteAdding()
    //      BlockingCollection<T>.GetConsumingEnumerable()
    let blockingCollectionGetConsumingEnumerable () =
        task {
            use bc = new BlockingCollection<int>()
            // Kick off a producer task
            let producerTask =
                task {
                    for i = 0 to 9 do
                        bc.Add i
                        printfn $"Producing: {i}"

                        do! Task.Delay 100 // sleep 100 ms between adds
                    // Need to do this to keep foreach below from hanging
                    bc.CompleteAdding()
                }

            // Now consume the blocking collection with foreach.
            // Use bc.GetConsumingEnumerable() instead of just bc because the
            // former will block waiting for completion and the latter will
            // simply take a snapshot of the current state of the underlying collection.
            for item in bc.GetConsumingEnumerable() do
                printfn $"Consuming: {item}"
            do! producerTask // Allow task to complete cleanup
        }
'Imports System.Threading.Tasks
'Imports System.Collections.Concurrent

' Demonstrates:
' BlockingCollection<T>.Add()
' BlockingCollection<T>.CompleteAdding()
' BlockingCollection<T>.GetConsumingEnumerable()

Class ConsumingEnumerableDemo
    Shared Sub BC_GetConsumingEnumerable()
        Using bc As New BlockingCollection(Of Integer)()

            ' Kick off a producer task
            Task.Factory.StartNew(
                Sub()
                    For i As Integer = 0 To 9
                        bc.Add(i)
                        ' sleep 100 ms between adds
                        Thread.Sleep(100)
                    Next

                    ' Need to do this to keep foreach below from not responding.
                    bc.CompleteAdding()
                End Sub)
            ' Now consume the blocking collection with foreach.
            ' Use bc.GetConsumingEnumerable() instead of just bc because the
            ' former will block waiting for completion and the latter will
            ' simply take a snapshot of the current state of the underlying collection.
            For Each item In bc.GetConsumingEnumerable()
                Console.WriteLine(item)
            Next
        End Using
    End Sub
End Class

См. также раздел

Применяется к