/// <inheritdoc /> public SubscriptionToken Subscribe <TEvent>(Action <TEvent> handler) where TEvent : EventBase { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } lock (this.subscriptionsLock) { if (!this.subscriptions.ContainsKey(typeof(TEvent))) { this.subscriptions.Add(typeof(TEvent), new List <ISubscription>()); } var subscriptionToken = new SubscriptionToken(this, typeof(TEvent)); this.subscriptions[typeof(TEvent)].Add(new Subscription <TEvent>(handler, subscriptionToken)); return(subscriptionToken); } }
/// <inheritdoc /> public void Unsubscribe(SubscriptionToken subscriptionToken) { // Ignore null token if (subscriptionToken == null) { this.logger.LogDebug("Unsubscribe called with a null token, ignored."); return; } lock (this.subscriptionsLock) { if (this.subscriptions.ContainsKey(subscriptionToken.EventType)) { List <ISubscription> allSubscriptions = this.subscriptions[subscriptionToken.EventType]; ISubscription subscriptionToRemove = allSubscriptions.FirstOrDefault(sub => sub.SubscriptionToken.Token == subscriptionToken.Token); if (subscriptionToRemove != null) { this.subscriptions[subscriptionToken.EventType].Remove(subscriptionToRemove); } } } }
/// <inheritdoc /> public SubscriptionToken Subscribe <TEvent>(Action <TEvent> handler) where TEvent : EventBase { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } lock (_subscriptionsLock) { if (!_subscriptions.ContainsKey(typeof(TEvent))) { _subscriptions.Add(typeof(TEvent), new List <ISubscription>()); } #pragma warning disable CA2000 // Dispose objects before losing scope var subscriptionToken = new SubscriptionToken(this, typeof(TEvent)); #pragma warning restore CA2000 // Dispose objects before losing scope _subscriptions[typeof(TEvent)].Add(new Subscription <TEvent>(handler, subscriptionToken)); return(subscriptionToken); } }
public Subscription(Action <TEventBase> action, SubscriptionToken token) { this.action = action ?? throw new ArgumentNullException(nameof(action)); this.SubscriptionToken = token ?? throw new ArgumentNullException(nameof(token)); }