Created
October 21, 2017 08:32
-
-
Save clemensv/58bfa9eeb4be771579ab5cc66c1fb9ef to your computer and use it in GitHub Desktop.
DynamicSemaphoreSlim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//--------------------------------------------------------------------------------- | |
// Copyright (c) Microsoft Corporation. | |
// | |
// MIT license. | |
//--------------------------------------------------------------------------------- | |
namespace ServiceBusPerfSample | |
{ | |
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
public class DynamicSemaphoreSlim : SemaphoreSlim | |
{ | |
const int overallocationCount = 10000; | |
long remainingOverallocation; | |
public DynamicSemaphoreSlim(int initialCount) : base(initialCount + overallocationCount) | |
{ | |
remainingOverallocation = overallocationCount; | |
// grab the overallocatedCounts | |
for (int i = 0; i < overallocationCount; i++) | |
{ | |
this.Wait(); | |
} | |
} | |
/// <summary> | |
/// Grant one more count | |
/// </summary> | |
public void Grant() | |
{ | |
if (Interlocked.Decrement(ref remainingOverallocation) < 0) | |
{ | |
throw new InvalidOperationException(); | |
} | |
this.Release(); | |
} | |
/// <summary> | |
/// Revoke a count once possible | |
/// </summary> | |
/// <returns>Task that completes when revocation is complete</returns> | |
public Task RevokeAsync() | |
{ | |
if (Interlocked.Increment(ref remainingOverallocation) > overallocationCount) | |
{ | |
throw new InvalidOperationException(); | |
} | |
return this.WaitAsync(); | |
} | |
/// <summary> | |
/// Revoke a count once possible (does not block) | |
/// </summary> | |
public void Revoke() | |
{ | |
if (Interlocked.Increment(ref remainingOverallocation) > overallocationCount) | |
{ | |
throw new InvalidOperationException(); | |
} | |
this.WaitAsync().ContinueWith((t)=> { }); // don't await | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is the empty
ContinueWith()
used for?