Skip to content

Instantly share code, notes, and snippets.

@sangram-chavan
Created December 29, 2023 14:49
Show Gist options
  • Select an option

  • Save sangram-chavan/d7982bffdb9e17cdd1d60cd0e94cc96d to your computer and use it in GitHub Desktop.

Select an option

Save sangram-chavan/d7982bffdb9e17cdd1d60cd0e94cc96d to your computer and use it in GitHub Desktop.

Revisions

  1. sangram-chavan created this gist Dec 29, 2023.
    37 changes: 37 additions & 0 deletions AsyncLock.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    [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();
    }
    }





    [MethodLocked(3)]
    public async Task AddUser(string username)
    {
    await _users.AddAsync(username);
    }


    }