MutexUtil.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. namespace gpt_api.Core.Utils;
  2. /// <summary>
  3. /// mutex公共方法
  4. /// </summary>
  5. public static class MutexUtil
  6. {
  7. /// <summary>
  8. /// mutex互斥锁
  9. /// 根据mutKey进行全局互斥,无等待,发现互斥直接报异常
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. /// <param name="mutKey"></param>
  13. /// <param name="action"></param>
  14. /// <returns></returns>
  15. public static T MutexNoWait<T>(string mutKey, Func<T> action)
  16. {
  17. bool isWait = false;
  18. using (Mutex mut = new Mutex(false, mutKey))
  19. {
  20. try
  21. {
  22. isWait = mut.WaitOne(0);
  23. if (!isWait)
  24. {
  25. throw Oops.Oh("当前接口存在正在进行中的访问");
  26. }
  27. return action();
  28. }
  29. finally
  30. {
  31. if (isWait)//WaitOne和ReleaseMutex成对出现
  32. {
  33. mut.ReleaseMutex();
  34. }
  35. }
  36. }
  37. }
  38. /// <summary>
  39. /// mutex互斥锁
  40. /// 根据mutKey进行全局互斥,无等待,发现互斥直接报异常
  41. /// </summary>
  42. /// <param name="mutKey"></param>
  43. /// <param name="action"></param>
  44. /// <returns></returns>
  45. public static void MutexNoWait(string mutKey, Action action)
  46. {
  47. bool isWait = false;
  48. using (Mutex mut = new Mutex(false, mutKey))
  49. {
  50. try
  51. {
  52. isWait = mut.WaitOne(0);
  53. if (!isWait)
  54. {
  55. throw Oops.Oh("当前接口存在正在进行中的访问");
  56. }
  57. action();
  58. }
  59. finally
  60. {
  61. if (isWait)//WaitOne和ReleaseMutex成对出现
  62. {
  63. mut.ReleaseMutex();
  64. }
  65. }
  66. }
  67. }
  68. }