SemaphoreWrapper.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace EVCB_OCPP.WSServer.Helper;
  8. public class SemaphoreWrapper : IDisposable
  9. {
  10. public async static Task<SemaphoreWrapper> WaitAsync(SemaphoreSlim semaphore)
  11. {
  12. var toReturn = new SemaphoreWrapper(semaphore);
  13. await semaphore.WaitAsync();
  14. toReturn.isLockAquired = true;
  15. return toReturn;
  16. }
  17. public async static Task<SemaphoreWrapper> TryGet(SemaphoreSlim semaphore)
  18. {
  19. var toReturn = new SemaphoreWrapper(semaphore);
  20. if (semaphore.Wait(0))
  21. {
  22. toReturn.isLockAquired = true;
  23. return toReturn;
  24. }
  25. return null;
  26. }
  27. private SemaphoreWrapper(SemaphoreSlim semaphore)
  28. {
  29. this.semaphore = semaphore;
  30. }
  31. public void Dispose()
  32. {
  33. if (isLockAquired)
  34. {
  35. semaphore.Release();
  36. }
  37. }
  38. private readonly SemaphoreSlim semaphore;
  39. private bool isLockAquired = false;
  40. }