diff --git a/TwitchLib.PubSub/TwitchPubSub.cs b/TwitchLib.PubSub/TwitchPubSub.cs index 4f8884a..ace1ac8 100644 --- a/TwitchLib.PubSub/TwitchPubSub.cs +++ b/TwitchLib.PubSub/TwitchPubSub.cs @@ -29,7 +29,7 @@ namespace TwitchLib.PubSub /// Implements the /// /// - public class TwitchPubSub : ITwitchPubSub + public class TwitchPubSub : ITwitchPubSub, IDisposable { private const string PingPayload = "{ \"type\": \"PING\" }"; @@ -73,6 +73,8 @@ public class TwitchPubSub : ITwitchPubSub private readonly Dictionary _topicToChannelId = new Dictionary(); + private bool _disposed = false; + #region Events /// /// @@ -1075,5 +1077,38 @@ public void TestMessageParser(string testJsonString) { ParseMessageAsync(testJsonString).GetAwaiter().GetResult(); } + + /// + /// Implement IDisposable. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual async void Dispose(bool disposing) + { + if (_disposed) + return; + + if (disposing) + { + await _socket.CloseAsync(); + _socket.Dispose(); + _previousRequestsSemaphore.Dispose(); + _pingTimer.Dispose(); + _pongTimer.Dispose(); + } + + _previousRequests.Clear(); + _topicList.Clear(); + _disposed = true; + } + + ~TwitchPubSub() + { + Dispose(false); + } } }