Search code examples
.netblockingcollection

Blocking collections operation and structs


I am using a BlockingCollection with a class of type T and I am wondering if I should turn T into a struct.

From the BlockingCollection signature in principle I do not see problems with that:

[DebuggerDisplay("Count = {Count}, Type = {m_collection}")]
[ComVisible(false)]
[DebuggerTypeProxy(typeof (SystemThreadingCollections_BlockingCollectionDebugView<>))]
[HostProtection(SecurityAction.LinkDemand, ExternalThreading = true, Synchronization = true)]
public class BlockingCollection<T> : IEnumerable<T>, ICollection, IEnumerable, IDisposable

However, the semantic of blocking operation take supporting cancellation is that it returns null if the operation is cancelled before an element becomes available. The problem here is that a structure can't be null, so the following code is invalid

Struct myStruct = collection.Take(cancellationToken);
if(myStruct!=null) ... code

Are therefore blocking collections limited to classes, or does the semantic change returning a non-initialized struct?


Solution

  • According to the documentation, Take doesn't return null if the operation is cancelled: an OperationCanceledException is thrown instead. Feel free to use any type, and be prepared to handle the exception if needed.