Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 2.79 KB

how-to-add-and-take-items.md

File metadata and controls

35 lines (25 loc) · 2.79 KB
description title ms.date dev_langs helpviewer_keywords ms.assetid
Learn more about: How to: Add and Take Items Individually from a BlockingCollection
How to: Add and Take Items Individually from a BlockingCollection
03/30/2017
csharp
vb
thread-safe collections, blocking dictionary
38f2f3d8-15e5-4bf4-9c83-2b5b6f22bad1

How to: Add and Take Items Individually from a BlockingCollection

This example shows how to add and remove items from a xref:System.Collections.Concurrent.BlockingCollection%601 in both a blocking and a non-blocking manner. For more information on xref:System.Collections.Concurrent.BlockingCollection%601, see BlockingCollection Overview.

For an example of how to enumerate a xref:System.Collections.Concurrent.BlockingCollection%601 until it is empty and no more elements will be added, see How to: Use ForEach to Remove Items in a BlockingCollection.

Example 1

This first example shows how to add and take items so that the operations will block if the collection is either temporarily empty (when taking) or at maximum capacity (when adding), or if a specified timeout period has elapsed. Note that blocking on maximum capacity is only enabled when the BlockingCollection has been created with a maximum capacity specified in the constructor.

[!code-csharpCDS_BlockingCollection#01] [!code-vbCDS_BlockingCollection#01]

Example 2

This second example shows how to add and take items so that the operations will not block. If no item is present, maximum capacity on a bounded collection has been reached, or the timeout period has elapsed, then the xref:System.Collections.Concurrent.BlockingCollection%601.TryAdd%2A or xref:System.Collections.Concurrent.BlockingCollection%601.TryTake%2A operation returns false. This allows the thread to do some other useful work for a while and then try again later to either retrieve a new item, or try to add the same item that could not be added previously. The program also demonstrates how to implement cancellation when accessing a xref:System.Collections.Concurrent.BlockingCollection%601.

[!code-csharpCDS_BlockingCollection#02] [!code-vbCDS_BlockingCollection#02]

See also