/// <summary> /// Remove a subscriber for a topic /// </summary> /// <param name="topic">Topic for unsubscription</param> /// <param name="client">Client to unsubscribe</param> public void Unsubscribe(string topic, MqttClient client) { string topicReplaced = topic.Replace(PLUS_WILDCARD, PLUS_WILDCARD_REPLACE).Replace(SHARP_WILDCARD, SHARP_WILDCARD_REPLACE); lock (this.subscribers) { // if the topic exists if (this.subscribers.ContainsKey(topicReplaced)) { // query for check client subscribed var query = from s in this.subscribers[topicReplaced] where s.ClientId == client.ClientId select s; // if the client is subscribed for the topic if (query.Count() > 0) { MqttSubscription subscription = query.First(); // remove subscription from the list for the topic this.subscribers[topicReplaced].Remove(subscription); // dispose subscription subscription.Dispose(); // remove topic if there aren't subscribers if (this.subscribers[topicReplaced].Count == 0) { this.subscribers.Remove(topicReplaced); } } } } }
/// <summary> /// Remove a subscriber for all topics /// </summary> /// <param name="client">Client to unsubscribe</param> public void Unsubscribe(MqttClient client) { lock (this.subscribers) { List <string> topicToRemove = new List <string>(); foreach (string topic in this.subscribers.Keys) { // query for check client subscribed var query = from s in this.subscribers[topic] where s.ClientId == client.ClientId select s; // if the client is subscribed for the topic if (query.Count() > 0) { MqttSubscription subscription = query.First(); // remove subscription from the list for the topic this.subscribers[topic].Remove(subscription); // dispose subscription subscription.Dispose(); // add topic to remove list if there aren't subscribers if (this.subscribers[topic].Count == 0) { topicToRemove.Add(topic); } } } // remove topic without subscribers // loop needed to avoid exception on modify collection inside previous loop foreach (string topic in topicToRemove) { this.subscribers.Remove(topic); } } }