/******************************************************************************** ** 类名称: SemaphorePool ** 描述 : 用于线程信号量的处理类 ** 作者 : 丁书杰 ** 创建时间:2019/03/26 ** 版权所有 (C) :中科视语(北京)科技有限公司 *********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace OS.Spin.Common.MultiThread { public class SemaphorePool { private Dictionary _sPool = new Dictionary(); private static SemaphorePool _cDk; private static readonly object ObjLock = new object(); public static SemaphorePool GetInstance() { lock (ObjLock) { return _cDk ?? (_cDk = new SemaphorePool()); } } /// /// 创建一个信号量 /// /// 信号量的名称 /// 并发信号量的个数 public void MakeSemaphore(string key, int multiThread = 1) { _sPool[key] = new Semaphore(0, multiThread); } /// /// 移出一个信号量 /// /// 需要移出信号量的名称 public void CleanSemaphore(string key) { if (!_sPool.Keys.Contains(key)) { return; } _sPool.Remove(key); } public bool Release(string key, int n = 1) { if(!_sPool.Keys.Contains(key)) { return true; } try { _sPool[key].Release(n); return true; } catch (Exception) { return false; } } public void Wait(string key) { if (!_sPool.Keys.Contains(key)) { return; } _sPool[key].WaitOne(); } } }