Created
December 29, 2023 14:49
-
-
Save sangram-chavan/d7982bffdb9e17cdd1d60cd0e94cc96d to your computer and use it in GitHub Desktop.
Using Locks using attribute in Async Await Scenario
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
[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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment