MutexExtensions.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Threading;
  3. namespace Update.Utils
  4. {
  5. public static class MutexExtensions
  6. {
  7. public delegate void DeleWriteLog(string txt);
  8. public static DeleWriteLog WriteLog;
  9. /// <summary>
  10. /// 进程间互斥操作
  11. /// </summary>
  12. /// <param name="key"></param>
  13. /// <param name="action"></param>
  14. /// <param name="recursive"></param>
  15. private static void Exec(string key, Action action, bool recursive)
  16. {
  17. using (Mutex mutex = new Mutex(initiallyOwned: false, name: key))
  18. {
  19. try
  20. {
  21. mutex.WaitOne();
  22. action();
  23. }
  24. catch (AbandonedMutexException ex)
  25. {
  26. if (recursive)
  27. {
  28. WriteLog?.Invoke(ex.Message);
  29. }
  30. else
  31. {
  32. Exec(key, action, true);
  33. }
  34. }
  35. finally
  36. {
  37. mutex.ReleaseMutex();
  38. }
  39. }
  40. }
  41. /// <summary>
  42. /// 进程间互斥操作
  43. /// </summary>
  44. /// <param name="key"></param>
  45. /// <param name="action"></param>
  46. public static void Exec(string key, Action action)
  47. {
  48. Exec(key, action, false);
  49. }
  50. }
  51. }