TaskMutexUtil.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 SHJX.Service.PortClient
  8. {
  9. /// <summary>
  10. /// 任务互斥锁工具类
  11. /// </summary>
  12. public class TaskMutexUtil : IDisposable
  13. {
  14. /// <summary>
  15. /// 定义一个互斥锁的实例
  16. /// </summary>
  17. private readonly Mutex mut;
  18. /// <summary>
  19. /// 判断是否已有相同名称的互斥锁存在 <para/>
  20. /// false:已存在,true:未存在
  21. /// </summary>
  22. public bool ResBool { get; set; }
  23. /// <param name="mutexKey">互斥锁名称</param>
  24. public TaskMutexUtil(string mutexKey)
  25. {
  26. mut = new Mutex(false, mutexKey, out bool res);
  27. ResBool = res;
  28. mut.WaitOne();
  29. }
  30. /// <summary>
  31. /// 释放
  32. /// </summary>
  33. public void Dispose()
  34. {
  35. //释放锁,让其他进程(或线程)得以继续执行
  36. mut.ReleaseMutex();
  37. //释放当前锁资源,为了避免互斥体占用唯一名称导致后续无法判断
  38. mut.Dispose();
  39. }
  40. }
  41. }