Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/mscorlib/src/System/Threading/SemaphoreSlim.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ public class SemaphoreSlim : IDisposable
// A pre-completed task with Result==true
private readonly static Task<bool> s_trueTask =
new Task<bool>(false, true, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken));
// A pre-completed task with Result==false
private readonly static Task<bool> s_falseTask =
new Task<bool>(false, false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken));

// No maximum constant
private const int NO_MAXIMUM = Int32.MaxValue;
Expand Down Expand Up @@ -320,6 +323,13 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)

cancellationToken.ThrowIfCancellationRequested();

// Perf: Check the stack timeout parameter before checking the volatile count
if (millisecondsTimeout == 0 && m_currentCount == 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a comment about why it's safe to be checking this outside of the lock.

{
// Pessimistic fail fast, check volatile count outside lock (only when timeout is zero!)
return false;
}

uint startTime = 0;
if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout > 0)
{
Expand Down Expand Up @@ -617,6 +627,11 @@ public Task<bool> WaitAsync(int millisecondsTimeout, CancellationToken cancellat
--m_currentCount;
if (m_waitHandle != null && m_currentCount == 0) m_waitHandle.Reset();
return s_trueTask;
}
else if (millisecondsTimeout == 0)
{
// No counts, if timeout is zero fail fast
return s_falseTask;
}
// If there aren't, create and return a task to the caller.
// The task will be completed either when they've successfully acquired
Expand Down