SemaphorePool.cs
2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/********************************************************************************
** 类名称: 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<string, Semaphore> _sPool = new Dictionary<string, Semaphore>();
private static SemaphorePool _cDk;
private static readonly object ObjLock = new object();
public static SemaphorePool GetInstance()
{
lock (ObjLock)
{
return _cDk ?? (_cDk = new SemaphorePool());
}
}
/// <summary>
/// 创建一个信号量
/// </summary>
/// <param name="key">信号量的名称</param>
/// <param name="multiThread">并发信号量的个数</param>
public void MakeSemaphore(string key, int multiThread = 1)
{
_sPool[key] = new Semaphore(0, multiThread);
}
/// <summary>
/// 移出一个信号量
/// </summary>
/// <param name="key">需要移出信号量的名称</param>
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();
}
}
}