-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathCounterActor.cs
63 lines (55 loc) · 1.99 KB
/
CounterActor.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
58
59
60
61
62
63
using System.Collections.Immutable;
using Akka.Actor;
using Akka.Event;
namespace AkkaWordCounter;
using static CounterQueries;
using static CounterCommands; // make message handlers less verbose
public sealed class CounterActor : UntypedActor{
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly Dictionary<string, int> _tokenCounts = new();
private bool _doneCounting = false;
// for actors who sent us a FetchCounts before we were done counting
private readonly HashSet<IActorRef> _subscribers = new();
protected override void OnReceive(object message){
switch(message){
case CountTokens tokens:
{
foreach(var t in tokens.Tokens){
if(!_tokenCounts.TryAdd(t, 1)){
_tokenCounts[t] += 1;
}
}
break;
}
case ExpectNoMoreTokens:
{
_doneCounting = true;
_log.Info("Completed counting tokens - found [{0}] unique tokens", _tokenCounts.Count);
// ensure the output is immutable
// cheaper to do this once at the end versus every time we count
var totals = _tokenCounts.ToImmutableDictionary();
foreach(var s in _subscribers)
{
s.Tell(totals);
}
// don't need to track subscribers anymore
_subscribers.Clear();
break;
}
case FetchCounts fetchCounts when _doneCounting:
{
// instantly reply with the results
fetchCounts.Subscriber.Tell(_tokenCounts.ToImmutableDictionary());
break;
}
case FetchCounts fetch:
{
_subscribers.Add(fetch.Subscriber);
break;
}
default:
Unhandled(message);
break;
}
}
}