-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsyncEventProcessor.cs
More file actions
82 lines (72 loc) · 2.83 KB
/
Copy pathAsyncEventProcessor.cs
File metadata and controls
82 lines (72 loc) · 2.83 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
82
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Disruptor;
using Disruptor.Dsl;
using System.Threading;
namespace DisruptorTest
{
public interface AsyncEventProcessorImplementation<T>
{
void OnNext(T @event, long sequence, bool endOfBatch, CancellationToken cancellationToken, Action<long> callback);
}
public sealed class AsyncEventProcessor<T> : AbstractEventProcessor<T> where T : class, new()
{
private readonly AsyncEventProcessorImplementation<T> _implementation;
private readonly ILock _lock;
private CancellationTokenSource _cancellationTokenSource;
private SortedSet<long> completed = new SortedSet<long>();
private long currentDownstreamBarrierSequence = -1L;
public AsyncEventProcessor(
RingBuffer<T> ringBuffer,
ISequenceBarrier sequenceBarrier,
ILock @lock,
AsyncEventProcessorImplementation<T> implementation
)
: base(ringBuffer, sequenceBarrier)
{
_implementation = implementation;
_lock = @lock;
_cancellationTokenSource = new CancellationTokenSource();
}
public override void OnNextAvaliable (T @event, long sequence, bool lastInBatch)
{
_implementation.OnNext(@event, sequence, lastInBatch, _cancellationTokenSource.Token, (s) => OnCompleted(s));
}
public override void OnCompleted(long sequence)
{
_lock.WithLock(() => {
completed.Add(sequence);
long newDownstreamBarrierSequence = ConsumeContiguousCompletedSequence();
if(newDownstreamBarrierSequence > currentDownstreamBarrierSequence)
{
currentDownstreamBarrierSequence = newDownstreamBarrierSequence;
base.OnCompleted(newDownstreamBarrierSequence);
}
});
}
private long ConsumeContiguousCompletedSequence ()
{
using (var enumerator = completed.GetEnumerator())
{
long completedSequence = currentDownstreamBarrierSequence;
while (enumerator.MoveNext() && enumerator.Current == completedSequence + 1)
{
completedSequence = enumerator.Current;
}
completed = new SortedSet<long>(completed.Where(x => x > completedSequence));
return completedSequence;
}
}
public override void Halt()
{
base.Halt();
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
}
}
}