What does BlockingCollection.Dispose actually do?
Asked
Active
Viewed 2,262 times
10
-
I encountered issues with disposing blocking collection (e.g. release the Take last time), until I started to use CancellationToken, see https://stackoverflow.com/a/5759866/1544054 – Aviko Mar 10 '18 at 09:51
3 Answers
13
This allows the internal wait handles to be disposed of properly.
BlockingCollection<T>
, internally, uses a pair of event wait handles, which in turn have an associated native HANDLE
.
Specifically, BlockingCollection<T>.Dispose()
releases these two handles back to the operating system, by eventually (through SemaphoreSlim->ManualResetEvent) calling the native CloseHandle method on the two native HANDLE
instances.

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
4
Having a quick look with reflector reveals this...
protected virtual void Dispose(bool disposing)
{
if (!this.m_isDisposed)
{
if (this.m_freeNodes != null)
{
this.m_freeNodes.Dispose();
}
this.m_occupiedNodes.Dispose();
this.m_isDisposed = true;
}
}
and m_freeNodes
is private SemaphoreSlim m_freeNodes;
so it releases the SemaphoreSlim that are used internally.

Andy Robinson
- 7,309
- 2
- 30
- 20