WaiterThreadLock.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 
  2. using System.Threading;
  3. namespace Curtain.Net.Sockets.PLC.ThreadLock
  4. {
  5. internal class WaiterThreadLock : IThreadLock
  6. {
  7. public bool Locked
  8. {
  9. get;
  10. private set;
  11. }
  12. private int _interlocke = 0;
  13. private readonly AutoResetEvent _waiterLock = new AutoResetEvent(false);
  14. public bool HasWaiter
  15. {
  16. get
  17. {
  18. return (_interlocke != 0);
  19. }
  20. }
  21. public void Dispose()
  22. {
  23. _waiterLock?.Close();
  24. }
  25. public bool Lock(int timeout = -1)
  26. {
  27. if (Interlocked.Increment(ref _interlocke) == 1)
  28. {
  29. return Locked = true;
  30. }
  31. if (timeout < 0)
  32. {
  33. //_waiterLock.WaitOne();
  34. return Locked = _waiterLock.WaitOne();
  35. }
  36. else
  37. {
  38. return Locked = _waiterLock.WaitOne(timeout);
  39. }
  40. }
  41. public void Unlock()
  42. {
  43. if (Interlocked.Decrement(ref _interlocke) == 0)
  44. {
  45. Locked = false;
  46. return;
  47. }
  48. _waiterLock.Set();
  49. Locked = false;
  50. }
  51. }
  52. }