Skip to content

Instantly share code, notes, and snippets.

@TheFo2sh
Last active September 16, 2019 23:11
Show Gist options
  • Save TheFo2sh/c3567a8e0a8f0435629f4c9835ae8d1e to your computer and use it in GitHub Desktop.
Save TheFo2sh/c3567a8e0a8f0435629f4c9835ae8d1e to your computer and use it in GitHub Desktop.
[Serializable]
public class MethodLockedAttribute : MethodInterceptionAspect
{
private int maximum_concurrency_number;
private static ConcurrentDictionary<int,SemaphoreSlim> SemaphoreSlimRepo=new ConcurrentDictionary<int, SemaphoreSlim>();
public MethodLockedAttribute(int maximumConcurrencyNumber)
{
maximum_concurrency_number = maximumConcurrencyNumber;
}
public override async Task OnInvokeAsync(MethodInterceptionArgs args)
{
SemaphoreSlim semaphore=new SemaphoreSlim(maximum_concurrency_number);
semaphore=SemaphoreSlimRepo.GetOrAdd(args.Method.GetMetadataToken(), semaphore);
await semaphore.WaitAsync();
try
{
await args.ProceedAsync();
}
finally
{
semaphore.Release();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment