-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathByteLoader.cs
More file actions
70 lines (52 loc) · 1.61 KB
/
Copy pathByteLoader.cs
File metadata and controls
70 lines (52 loc) · 1.61 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
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace PictureView;
class ByteLoader
{
private (FileSystemImage image, SemaphoreSlim ss) currentTuple;
private readonly Queue<(FileSystemImage image, SemaphoreSlim ss)> queue;
public CancellationTokenSource CancelSource { get; }
public ByteLoader()
{
queue = new Queue<(FileSystemImage image, SemaphoreSlim ss)>();
CancelSource = new CancellationTokenSource();
Task.Factory.StartNew(BytesLoad, CancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
private async Task BytesLoad()
{
while (!CancelSource.Token.IsCancellationRequested)
{
lock (queue)
{
while (queue.Count == 0)
{
Monitor.Wait(queue);
}
currentTuple = queue.Dequeue();
}
await currentTuple.image.LoadBytes();
currentTuple.ss.Release();
}
}
public async Task<bool> Load(FileSystemImage? image)
{
if (image == null) return false;
SemaphoreSlim ss = new SemaphoreSlim(0, 1);
lock (queue)
{
if (Contains(image)) return false;
queue.Enqueue((image, ss));
Monitor.Pulse(queue);
}
await ss.WaitAsync();
ss.Dispose();
return true;
}
private bool Contains(FileSystemImage image)
{
if (image == currentTuple.image) return true;
return queue.Any(t => t.image == image);
}
}