dotnet / dotnet/dotnet-api-docs
BlockingCollection incorrect documentation or a bug in .Net?
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
On this page: https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.blockingcollection-1.trytake?view=netframework-4.8 (Source XML in this repository: https://github.com/dotnet/dotnet-api-docs/blob/master/xml/System.Collections.Concurrent/BlockingCollection%601.xml )
`TryTake(T) ` **Remarks** note that:
> If the collection is empty, this method immediately returns false
However this remark is *not* present in any of the following API `TryTake(T, TimeSpan)`, `TryTake(T, Int32, CancellationToken)` or `TryTake(T, Int32)` remarks.
However based on my testing (.Net Framework 4.8) it appears that `TryTake(T, Int32, CancellationToken)` will *also* return instantly with `false` if the BlockingCollection is empty. Now, personally this makes no sense to me, I have specified a timeout I am willing to wait for data so why is it returning instantly?
The following code results in a CPU eating instant loop.
```csharp
private readonly BlockingCollection _encodedAudioPacketByes = new BlockingCollection();
private readonly CancellationTokenSource _stopFlag = new CancellationTokenSource();
while (!cancellationToken.IsCancellationRequested)
{
_encodedAudio .TryTake(out var encodedOpusAudio, Timeout.Infinite, cancellationToken);
}
```
while the following doesn't
```csharp
private readonly BlockingCollection _encodedAudioPacketByes = new BlockingCollection();
private readonly CancellationTokenSource _stopFlag = new CancellationTokenSource();
while (!cancellationToken.IsCancellationRequested)
{
Thread.sleep(50)
if(_encodedAudioPacketByes.Count == 0) continue;
_encodedAudioPacketByes.TryTake(out var encodedOpusAudio, Timeout.Infinite, cancellationToken);
}
```
I am leaning towards this being a bug in .Net but since I am relatively inexperienced in C# I am leaving this issue here as a documentation issue pending confirmation of: documentation issue, bug, or I am an idiot and missing something.
If it *is* behaving as expected then update documentation for all API calls with the
> If the collection is empty, this method immediately returns false
remark
Contributor guide
Assessment
This issue has not been assessed yet.