-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlocksHandler.cs
More file actions
64 lines (55 loc) · 1.61 KB
/
BlocksHandler.cs
File metadata and controls
64 lines (55 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
using System;
using System.Security.Cryptography;
using System.Threading;
namespace FileSignature
{
internal class BlocksHandler
{
private readonly SemaphoreSlim _handledCounter;
private readonly BufferedTextWriter _writer;
private readonly int _counterStartValue;
private int _noBlocksExpected;
public ManualResetEvent WorkDoneAwaiter;
public BlocksHandler(SemaphoreSlim handledCounter, BufferedTextWriter writer)
{
if (handledCounter == null) throw new ArgumentNullException(nameof(handledCounter));
if (writer == null) throw new ArgumentNullException(nameof(writer));
_handledCounter = handledCounter;
_writer = writer;
_counterStartValue = handledCounter.CurrentValue;
WorkDoneAwaiter = new ManualResetEvent(false);
}
private static string ToOutputFormat(Block block)
{
using (var sha256 = SHA256.Create())
{
var hash = sha256.ComputeHash(block.Bytes, 0, block.Size);
var output = BitConverter.ToString(hash).Replace("-","");
return output;
}
}
private void HandleBlock(Block block)
{
string blockString = ToOutputFormat(block);
_writer.Write(block.Number, blockString);
_handledCounter.Release();
UpdateAwaiter();
}
private void UpdateAwaiter()
{
Thread.MemoryBarrier();
if (Thread.VolatileRead(ref _noBlocksExpected) != 0)
if (_counterStartValue == _handledCounter.CurrentValue)
WorkDoneAwaiter.Set();
}
public void HandleBlockAsync(Block block)
{
FixedSizeThreadPool.QueueAction(() => HandleBlock(block));
}
public void EndOfBlocks()
{
Interlocked.Exchange(ref _noBlocksExpected, 1);
UpdateAwaiter();
}
}
}