LockerList.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. namespace Island.StandardLib.Utils
  8. {
  9. /// <summary>
  10. /// 一组不精确的非原子锁
  11. /// </summary>
  12. /// <typeparam name="LockIdType">锁定项标识,需要实现 <see cref="object.GetHashCode()"/></typeparam>
  13. public class LockerList<LockIdType>
  14. {
  15. readonly ConcurrentDictionary<LockIdType, bool> mapLck;
  16. readonly object globalLck;
  17. public LockerList()
  18. {
  19. mapLck = new ConcurrentDictionary<LockIdType, bool>();
  20. globalLck = new object();
  21. }
  22. /// <summary>
  23. /// 加读锁
  24. /// </summary>
  25. /// <param name="lckId">标识</param>
  26. public void Lock(LockIdType lckId)
  27. {
  28. if (mapLck.TryGetValue(lckId, out bool __lck))
  29. {
  30. do Thread.Sleep(1);
  31. while (__lck);
  32. lock (globalLck) mapLck[lckId] = true;
  33. }
  34. else
  35. {
  36. lock (globalLck) mapLck.TryAdd(lckId, true);
  37. }
  38. }
  39. /// <summary>
  40. /// 解锁
  41. /// </summary>
  42. /// <param name="lckId">标识</param>
  43. public void Unlock(LockIdType lckId)
  44. {
  45. lock (globalLck) mapLck[lckId] = false;
  46. }
  47. }
  48. }