diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs index e4ec98502a72f5..eba5ed1b6b8dcb 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs @@ -603,6 +603,14 @@ public bool TryTake([MaybeNullWhen(false)] out T item) public bool TryTake([MaybeNullWhen(false)] out T item, TimeSpan timeout) { ValidateTimeout(timeout); + + // If the collection is completed then there is no need remove an item. + if (IsCompleted) + { + item = default(T); + return false; + } + return TryTakeWithNoTimeValidation(out item, (int)timeout.TotalMilliseconds, CancellationToken.None, null); } @@ -624,6 +632,14 @@ public bool TryTake([MaybeNullWhen(false)] out T item, TimeSpan timeout) public bool TryTake([MaybeNullWhen(false)] out T item, int millisecondsTimeout) { ValidateMillisecondsTimeout(millisecondsTimeout); + + // If the collection is completed then there is no need remove an item. + if (IsCompleted) + { + item = default(T); + return false; + } + return TryTakeWithNoTimeValidation(out item, millisecondsTimeout, CancellationToken.None, null); } @@ -649,6 +665,15 @@ public bool TryTake([MaybeNullWhen(false)] out T item, int millisecondsTimeout) public bool TryTake([MaybeNullWhen(false)] out T item, int millisecondsTimeout, CancellationToken cancellationToken) { ValidateMillisecondsTimeout(millisecondsTimeout); + + cancellationToken.ThrowIfCancellationRequested(); + // If the collection is completed then there is no need remove an item. + if (IsCompleted) + { + item = default(T); + return false; + } + return TryTakeWithNoTimeValidation(out item, millisecondsTimeout, cancellationToken, null); } @@ -670,16 +695,9 @@ public bool TryTake([MaybeNullWhen(false)] out T item, int millisecondsTimeout, /// If the collection has been disposed. private bool TryTakeWithNoTimeValidation([MaybeNullWhen(false)] out T item, int millisecondsTimeout, CancellationToken cancellationToken, CancellationTokenSource? combinedTokenSource) { - CheckDisposed(); + Debug.Assert(!_isDisposed); item = default(T)!; - cancellationToken.ThrowIfCancellationRequested(); - - //If the collection is completed then there is no need to wait. - if (IsCompleted) - { - return false; - } bool waitForSemaphoreWasSuccessful = false; // set the combined token source to the combinedToken parameter if it is not null (came from GetConsumingEnumerable) @@ -1645,6 +1663,7 @@ public IEnumerable GetConsumingEnumerable() /// If the is canceled. public IEnumerable GetConsumingEnumerable(CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); CancellationTokenSource? linkedTokenSource = null; try {