123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- namespace gpt_api.Core.Utils;
- /// <summary>
- /// mutex公共方法
- /// </summary>
- public static class MutexUtil
- {
- /// <summary>
- /// mutex互斥锁
- /// 根据mutKey进行全局互斥,无等待,发现互斥直接报异常
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="mutKey"></param>
- /// <param name="action"></param>
- /// <returns></returns>
- public static T MutexNoWait<T>(string mutKey, Func<T> action)
- {
- bool isWait = false;
- using (Mutex mut = new Mutex(false, mutKey))
- {
- try
- {
- isWait = mut.WaitOne(0);
- if (!isWait)
- {
- throw Oops.Oh("当前接口存在正在进行中的访问");
- }
- return action();
- }
- finally
- {
- if (isWait)//WaitOne和ReleaseMutex成对出现
- {
- mut.ReleaseMutex();
- }
- }
- }
- }
- /// <summary>
- /// mutex互斥锁
- /// 根据mutKey进行全局互斥,无等待,发现互斥直接报异常
- /// </summary>
- /// <param name="mutKey"></param>
- /// <param name="action"></param>
- /// <returns></returns>
- public static void MutexNoWait(string mutKey, Action action)
- {
- bool isWait = false;
- using (Mutex mut = new Mutex(false, mutKey))
- {
- try
- {
- isWait = mut.WaitOne(0);
- if (!isWait)
- {
- throw Oops.Oh("当前接口存在正在进行中的访问");
- }
- action();
- }
- finally
- {
- if (isWait)//WaitOne和ReleaseMutex成对出现
- {
- mut.ReleaseMutex();
- }
- }
- }
- }
- }
|