Dreamine.Communication.Core 1.0.2
Dreamine.Communication.Core 통신 기능과 관련 API를 제공합니다.
로딩중...
검색중...
일치하는것 없음
MessageRouter.cs
이 파일의 문서화 페이지로 가기
1using System;
2using System.Collections.Concurrent;
3using System.Collections.Generic;
4using System.Threading;
5using System.Threading.Tasks;
6using Dreamine.Communication.Abstractions.Interfaces;
7using Dreamine.Communication.Abstractions.Models;
8
10
19public sealed class MessageRouter : IMessageRouter
20{
29 private readonly ConcurrentDictionary<string, List<Func<MessageEnvelope, CancellationToken, Task>>> _handlers = new();
30
71 public void Register(
72 string route,
73 Func<MessageEnvelope, CancellationToken, Task> handler)
74 {
75 ArgumentException.ThrowIfNullOrWhiteSpace(route);
76 ArgumentNullException.ThrowIfNull(handler);
77
78 var handlers = _handlers.GetOrAdd(
79 route,
80 _ => new List<Func<MessageEnvelope, CancellationToken, Task>>());
81
82 lock (handlers)
83 {
84 handlers.Add(handler);
85 }
86 }
87
136 public bool Unregister(
137 string route,
138 Func<MessageEnvelope, CancellationToken, Task> handler)
139 {
140 ArgumentException.ThrowIfNullOrWhiteSpace(route);
141 ArgumentNullException.ThrowIfNull(handler);
142
143 if (!_handlers.TryGetValue(route, out var handlers))
144 {
145 return false;
146 }
147
148 lock (handlers)
149 {
150 var removed = handlers.Remove(handler);
151
152 if (handlers.Count == 0)
153 {
154 _handlers.TryRemove(route, out _);
155 }
156
157 return removed;
158 }
159 }
160
209 public async Task RouteAsync(
210 MessageEnvelope message,
211 CancellationToken cancellationToken = default)
212 {
213 ArgumentNullException.ThrowIfNull(message);
214
215 if (!_handlers.TryGetValue(message.Route, out var handlers))
216 {
217 return;
218 }
219
220 List<Func<MessageEnvelope, CancellationToken, Task>> snapshot;
221
222 lock (handlers)
223 {
224 snapshot = new List<Func<MessageEnvelope, CancellationToken, Task>>(handlers);
225 }
226
227 foreach (var handler in snapshot)
228 {
229 cancellationToken.ThrowIfCancellationRequested();
230 await handler(message, cancellationToken).ConfigureAwait(false);
231 }
232 }
233
242 public void Clear()
243 {
244 _handlers.Clear();
245 }
246}
bool Unregister(string route, Func< MessageEnvelope, CancellationToken, Task > handler)
async Task RouteAsync(MessageEnvelope message, CancellationToken cancellationToken=default)
readonly ConcurrentDictionary< string, List< Func< MessageEnvelope, CancellationToken, Task > > > _handlers
void Register(string route, Func< MessageEnvelope, CancellationToken, Task > handler)