Skip to content

Instantly share code, notes, and snippets.

@clemensv
Created October 21, 2017 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clemensv/58bfa9eeb4be771579ab5cc66c1fb9ef to your computer and use it in GitHub Desktop.
Save clemensv/58bfa9eeb4be771579ab5cc66c1fb9ef to your computer and use it in GitHub Desktop.
DynamicSemaphoreSlim
//---------------------------------------------------------------------------------
// 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
}
}
}
@lothrop
Copy link

lothrop commented Feb 15, 2018

What is the empty ContinueWith() used for?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment