Skip to content

Instantly share code, notes, and snippets.

@danielmarbach
Created May 8, 2017 15:53
Show Gist options
  • Save danielmarbach/02bbda7411a9b789ea99282811c738fb to your computer and use it in GitHub Desktop.
Save danielmarbach/02bbda7411a9b789ea99282811c738fb to your computer and use it in GitHub Desktop.
Simple Semaphore Usage
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Semaphore
{
class Program
{
static void Main(string[] args)
{
Do();
Console.ReadLine();
}
private static void Do()
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var concurrency = 10;
var semaphore = new SemaphoreSlim(concurrency);
Task.Run(async () =>
{
while (!cts.IsCancellationRequested)
{
await semaphore.WaitAsync(cts.Token);
SimulateWork(semaphore, cts.Token).IgnoreContinuation();
}
});
}
static async Task SimulateWork(SemaphoreSlim semaphore, CancellationToken token)
{
try
{
await Task.Delay(500, token);
Console.Write(".");
}
catch (OperationCanceledException)
{
// graceful shutdown
Console.Write("!");
}
finally
{
semaphore.Release();
}
}
}
static class TaskExtensions
{
public static void IgnoreContinuation(this Task task)
{
task.ContinueWith(t =>
{
var exception = t.Exception;
Console.Error.WriteLine(exception?.Message);
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment