| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace SHJX.Service.PortClient
- {
- /// <summary>
- /// 任务互斥锁工具类
- /// </summary>
- public class TaskMutexUtil : IDisposable
- {
- /// <summary>
- /// 定义一个互斥锁的实例
- /// </summary>
- private readonly Mutex mut;
- /// <summary>
- /// 判断是否已有相同名称的互斥锁存在 <para/>
- /// false:已存在,true:未存在
- /// </summary>
- public bool ResBool { get; set; }
- /// <param name="mutexKey">互斥锁名称</param>
- public TaskMutexUtil(string mutexKey)
- {
- mut = new Mutex(false, mutexKey, out bool res);
- ResBool = res;
- mut.WaitOne();
- }
- /// <summary>
- /// 释放
- /// </summary>
- public void Dispose()
- {
- //释放锁,让其他进程(或线程)得以继续执行
- mut.ReleaseMutex();
- //释放当前锁资源,为了避免互斥体占用唯一名称导致后续无法判断
- mut.Dispose();
- }
- }
- }
|