Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/csharp/events_delegates.txt

1.9 KiB, 1 run

created by r1870400018:11962, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1using System;
2using System.Collections.Generic;
3
4namespace Annealer.Examples
5{
6 public class EventBus
7 {
8 private readonly Dictionary<string, List<Action<object>>> _handlers = new();
9
10 public void Subscribe(string topic, Action<object> handler)
11 {
12 if (!_handlers.ContainsKey(topic))
13 _handlers[topic] = new List<Action<object>>();
14 _handlers[topic].Add(handler);
15 }
16
17 public void Publish(string topic, object payload)
18 {
19 if (!_handlers.TryGetValue(topic, out var handlers))
20 return;
21 foreach (var handler in handlers)
22 {
23 try
24 {
25 handler(payload);
26 }
27 catch (Exception ex)
28 {
29 Console.WriteLine($"handler error on {topic}: {ex.Message}");
30 }
31 }
32 }
33
34 public int HandlerCount(string topic)
35 {
36 return _handlers.TryGetValue(topic, out var handlers)
37 ? handlers.Count
38 : 0;
39 }
40 }
41
42 internal class Ticker
43 {
44 public event EventHandler<int>? Ticked;
45 private int _count;
46
47 public void Tick()
48 {
49 _count++;
50 Ticked?.Invoke(this, _count);
51 }
52 }
53
54 class Program
55 {
56 static void Main()
57 {
58 var bus = new EventBus();
59 bus.Subscribe("log", msg => Console.WriteLine($"LOG: {msg}"));
60 bus.Subscribe("log", msg => Console.WriteLine($"AUDIT: {msg}"));
61 bus.Publish("log", "application started");
62
63 var ticker = new Ticker();
64 ticker.Ticked += (sender, count) =>
65 Console.WriteLine($"tick #{count}");
66 ticker.Tick();
67 ticker.Tick();
68 ticker.Tick();
69 }
70 }
71}