Export (0) Print
Expand All

BlockingCollection<T>.TryTake Method

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  NameDescription
Public method TryTake(T) Tries to remove an item from the BlockingCollection<T>.
Public method TryTake(T, Int32) Tries to remove an item from the BlockingCollection<T> in the specified time period.
Public method TryTake(T, TimeSpan) Tries to remove an item from the BlockingCollection<T> in the specified time period.
Public method TryTake(T, Int32, CancellationToken) Tries to remove an item from the BlockingCollection<T> in the specified time period while observing a cancellation token.
Top

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 / 2) * (NUMITEMS - 1));
            Console.WriteLine("bc.IsCompleted = {0} (should be true)", bc.IsCompleted);
        }
    }
}


Community Additions

ADD
Show:
© 2015 Microsoft