Reduce overhead of SemaphoreSlim.WaitAsync (#24687)
authorStephen Toub <stoub@microsoft.com>
Tue, 21 May 2019 22:00:53 +0000 (18:00 -0400)
committerGitHub <noreply@github.com>
Tue, 21 May 2019 22:00:53 +0000 (18:00 -0400)
commit26533de63976cb34eb1224c903128e398ca887d9
tree64302202eecc183a229ab1ab8c2f45498002a04a
parent9f75e67e8c102c49e690116d38de25cece3452a9
Reduce overhead of SemaphoreSlim.WaitAsync (#24687)

This affects the case where SemaphoreSlim.WaitAsync is invoked, the operation completes asynchronously because there's no count available in the semaphore, and where a timeout and/or a cancellation token is passed to WaitAsync.  In that case, we need to wait for the underlying wait task to complete, for cancellation to be requested, or for the timeout to elapse.

There's currently one code path that handles this.  This change improves that slightly by avoiding a defensive array copy.  However, we can do much better when we get a cancelable token but no timeout, in which case we can avoid operations like Task.Delay, can register with the original cancellation token rather than a new one (which means we avoid forcing a new CancellationTokenSource's lazily-allocated partitions into existence), etc.
src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs