| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- using System;
- using System.Threading;
- namespace Update.Utils
- {
- public static class MutexExtensions
- {
- public delegate void DeleWriteLog(string txt);
- public static DeleWriteLog WriteLog;
- /// <summary>
- /// 进程间互斥操作
- /// </summary>
- /// <param name="key"></param>
- /// <param name="action"></param>
- /// <param name="recursive"></param>
- private static void Exec(string key, Action action, bool recursive)
- {
- using (Mutex mutex = new Mutex(initiallyOwned: false, name: key))
- {
- try
- {
- mutex.WaitOne();
- action();
- }
- catch (AbandonedMutexException ex)
- {
- if (recursive)
- {
- WriteLog?.Invoke(ex.Message);
- }
- else
- {
- Exec(key, action, true);
- }
- }
- finally
- {
- mutex.ReleaseMutex();
- }
- }
- }
- /// <summary>
- /// 进程间互斥操作
- /// </summary>
- /// <param name="key"></param>
- /// <param name="action"></param>
- public static void Exec(string key, Action action)
- {
- Exec(key, action, false);
- }
- }
- }
|