Редагувати

Поділитися через


BlockingCollection<T>.TryTake Method

Definition

Tries to remove an item from the BlockingCollection<T>.

Overloads

TryTake(T)

Tries to remove an item from the BlockingCollection<T>.

TryTake(T, TimeSpan)

Tries to remove an item from the BlockingCollection<T> in the specified time period.

TryTake(T, Int32, CancellationToken)

Tries to remove an item from the BlockingCollection<T> in the specified time period while observing a cancellation token.

TryTake(T, Int32)

Tries to remove an item from the BlockingCollection<T> in the specified time period.

Examples

The following example shows how to use the TryTake method.

class TryTakeDemo
{
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.CompleteAdding()
    //      BlockingCollection<T>.TryTake()
    //      BlockingCollection<T>.IsCompleted
    public static void BC_TryTake()
    {
        // Construct and fill our BlockingCollection
        using (BlockingCollection<int> bc = new BlockingCollection<int>())
        {
            int NUMITEMS = 10000;
            for (int i = 0; i < NUMITEMS; i++) bc.Add(i);
            bc.CompleteAdding();
            int outerSum = 0;

            // Delegate for consuming the BlockingCollection and adding up all items
            Action action = () =>
            {
                int localItem;
                int localSum = 0;

                while (bc.TryTake(out localItem)) localSum += localItem;
                Interlocked.Add(ref outerSum, localSum);
            };

            // Launch three parallel actions to consume the BlockingCollection
            Parallel.Invoke(action, action, action);

            Console.WriteLine("Sum[0..{0}) = {1}, should be {2}", NUMITEMS, outerSum, ((NUMITEMS * (NUMITEMS - 1)) / 2));
            Console.WriteLine("bc.IsCompleted = {0} (should be true)", bc.IsCompleted);
        }
    }
}
module TryTakeDemo =
    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.CompleteAdding()
    //      BlockingCollection<T>.TryTake()
    //      BlockingCollection<T>.IsCompleted
    let blockingCollectionTryTake () =
        // Construct and fill our BlockingCollection
        use bc = new BlockingCollection<int>()
        let NUMITEMS = 10000;
        for i = 0 to NUMITEMS - 1 do
            bc.Add i
        bc.CompleteAdding()
        let mutable outerSum = 0

        // Delegate for consuming the BlockingCollection and adding up all items
        let action = 
            Action(fun () ->
                let mutable localItem = 0
                let mutable localSum = 0

                while bc.TryTake &localItem do
                    localSum <- localSum + localItem
                Interlocked.Add(&outerSum, localSum)
                |> ignore)

        // Launch three parallel actions to consume the BlockingCollection
        Parallel.Invoke(action, action, action)

        printfn $"Sum[0..{NUMITEMS}) = {outerSum}, should be {((NUMITEMS * (NUMITEMS - 1)) / 2)}"
        printfn $"bc.IsCompleted = {bc.IsCompleted} (should be true)"
'Imports System.Collections.Concurrent
'Imports System.Threading
'Imports System.Threading.Tasks

Class TryTakeDemo
    ' Demonstrates:
    ' BlockingCollection<T>.Add()
    ' BlockingCollection<T>.CompleteAdding()
    ' BlockingCollection<T>.TryTake()
    ' BlockingCollection<T>.IsCompleted
    Shared Sub BC_TryTake()
        ' Construct and fill our BlockingCollection
        Using bc As New BlockingCollection(Of Integer)()
            Dim NUMITEMS As Integer = 10000
            For i As Integer = 0 To NUMITEMS - 1
                bc.Add(i)
            Next
            bc.CompleteAdding()
            Dim outerSum As Integer = 0

            ' Delegate for consuming the BlockingCollection and adding up all items
            Dim action As Action =
                Sub()
                    Dim localItem As Integer
                    Dim localSum As Integer = 0

                    While bc.TryTake(localItem)
                        localSum += localItem
                    End While
                    Interlocked.Add(outerSum, localSum)
                End Sub

            ' Launch three parallel actions to consume the BlockingCollection
            Parallel.Invoke(action, action, action)

            Console.WriteLine("Sum[0..{0}) = {1}, should be {2}", NUMITEMS, outerSum, ((NUMITEMS * (NUMITEMS - 1)) / 2))
            Console.WriteLine("bc.IsCompleted = {0} (should be true)", bc.IsCompleted)
        End Using
    End Sub

End Class

TryTake(T)

Source:
BlockingCollection.cs
Source:
BlockingCollection.cs
Source:
BlockingCollection.cs

Tries to remove an item from the BlockingCollection<T>.

public:
 bool TryTake([Runtime::InteropServices::Out] T % item);
public bool TryTake (out T item);
member this.TryTake : 'T -> bool
Public Function TryTake (ByRef item As T) As Boolean

Parameters

item
T

The item to be removed from the collection.

Returns

true if an item could be removed; otherwise, false.

Exceptions

The underlying collection was modified outside of this BlockingCollection<T> instance.

Remarks

If the collection is empty, this method immediately returns false.

The order in which an item is removed depends on the type of collection used to create the BlockingCollection<T> instance. When you create a BlockingCollection<T> object, you can specify the type of collection to use. For example, you could specify a ConcurrentQueue<T> object for first in, first out (FIFO) behavior, or a ConcurrentStack<T> object for last in, first out (LIFO) behavior. You can use any collection class that implements the IProducerConsumerCollection<T> interface. The default collection type for BlockingCollection<T> is ConcurrentQueue<T>.

See also

Applies to

TryTake(T, TimeSpan)

Source:
BlockingCollection.cs
Source:
BlockingCollection.cs
Source:
BlockingCollection.cs

Tries to remove an item from the BlockingCollection<T> in the specified time period.

public:
 bool TryTake([Runtime::InteropServices::Out] T % item, TimeSpan timeout);
public bool TryTake (out T item, TimeSpan timeout);
member this.TryTake : 'T * TimeSpan -> bool
Public Function TryTake (ByRef item As T, timeout As TimeSpan) As Boolean

Parameters

item
T

The item to be removed from the collection.

timeout
TimeSpan

A TimeSpan that represents the number of milliseconds to wait for the item to be removed, or a TimeSpan that represents -1 milliseconds to wait indefinitely.

Returns

true if an item could be removed from the collection within the specified time; otherwise, false.

Exceptions

timeout is a negative number other than -1 milliseconds, which represents an infinite time-out.

-or-

timeout is greater than Int32.MaxValue.

The underlying collection was modified outside of this BlockingCollection<T> instance.

Remarks

The order in which an item is removed depends on the type of collection used to create the BlockingCollection<T> instance. When you create a BlockingCollection<T> object, you can specify the type of collection to use. For example, you could specify a ConcurrentQueue<T> object for first in, first out (FIFO) behavior, or a ConcurrentStack<T> object for last in, first out (LIFO) behavior. You can use any collection class that implements the IProducerConsumerCollection<T> interface. The default collection type for BlockingCollection<T> is ConcurrentQueue<T>.

See also

Applies to

TryTake(T, Int32, CancellationToken)

Source:
BlockingCollection.cs
Source:
BlockingCollection.cs
Source:
BlockingCollection.cs

Tries to remove an item from the BlockingCollection<T> in the specified time period while observing a cancellation token.

public:
 bool TryTake([Runtime::InteropServices::Out] T % item, int millisecondsTimeout, System::Threading::CancellationToken cancellationToken);
public bool TryTake (out T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken);
member this.TryTake : 'T * int * System.Threading.CancellationToken -> bool
Public Function TryTake (ByRef item As T, millisecondsTimeout As Integer, cancellationToken As CancellationToken) As Boolean

Parameters

item
T

The item to be removed from the collection.

millisecondsTimeout
Int32

The number of milliseconds to wait for the item to be removed, or Infinite (-1) to wait indefinitely.

cancellationToken
CancellationToken

A cancellation token to observe.

Returns

true if an item could be removed from the collection within the specified time; otherwise, false.

Exceptions

The BlockingCollection<T> has been disposed or the underlying CancellationTokenSource has been disposed.

millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

The underlying collection was modified outside this BlockingCollection<T> instance.

Remarks

The order in which an item is removed depends on the type of collection used to create the BlockingCollection<T> instance. When you create a BlockingCollection<T> object, you can specify the type of collection to use. For example, you could specify a ConcurrentQueue<T> object for first in, first out (FIFO) behavior, or a ConcurrentStack<T> object for last in, first out (LIFO) behavior. You can use any collection class that implements the IProducerConsumerCollection<T> interface. The default collection type for BlockingCollection<T> is ConcurrentQueue<T>.

See also

Applies to

TryTake(T, Int32)

Source:
BlockingCollection.cs
Source:
BlockingCollection.cs
Source:
BlockingCollection.cs

Tries to remove an item from the BlockingCollection<T> in the specified time period.

public:
 bool TryTake([Runtime::InteropServices::Out] T % item, int millisecondsTimeout);
public bool TryTake (out T item, int millisecondsTimeout);
member this.TryTake : 'T * int -> bool
Public Function TryTake (ByRef item As T, millisecondsTimeout As Integer) As Boolean

Parameters

item
T

The item to be removed from the collection.

millisecondsTimeout
Int32

The number of milliseconds to wait for the item to be removed, or Infinite (-1) to wait indefinitely.

Returns

true if an item could be removed from the collection within the specified time; otherwise, false.

Exceptions

millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

The underlying collection was modified outside of this BlockingCollection<T> instance.

Remarks

The order in which an item is removed depends on the type of collection used to create the BlockingCollection<T> instance. When you create a BlockingCollection<T>, you can specify the type of collection to use. For example, you could specify a ConcurrentQueue<T> object for first in, first out (FIFO) behavior, or a ConcurrentStack<T> object for last in, first out (LIFO) behavior. You can use any collection class that implements the IProducerConsumerCollection<T> interface. The default collection type for BlockingCollection<T> is ConcurrentQueue<T>.

See also

Applies to