-
-
Save danielmarbach/02bbda7411a9b789ea99282811c738fb to your computer and use it in GitHub Desktop.
Simple Semaphore Usage
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
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