-
Notifications
You must be signed in to change notification settings - Fork 0
/
TaskLocker.cs
57 lines (48 loc) · 1.22 KB
/
TaskLocker.cs
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
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TaskLocker
{
public class TaskLocker : IDisposable
{
private readonly object _syncRoot = new object();
private readonly Queue<Task> _waitingQueue = new Queue<Task>();
private bool _isLocked = false;
private void DoNoting()
{
}
public Task Enter()
{
lock (_syncRoot)
{
if (_isLocked)
{
Task waitingOne = new Task(DoNoting);
_waitingQueue.Enqueue(waitingOne);
return waitingOne;
}
_isLocked = true;
return Task.CompletedTask;
}
}
public void Leave()
{
lock (_syncRoot)
{
if (_waitingQueue.Count == 0)
{
_isLocked = false;
}
else
{
Task oneGotLock = _waitingQueue.Dequeue();
oneGotLock.Start();
}
}
}
public void Dispose()
{
Leave();
}
}
}