From 4da01ff744391d9c284467517f5a4cd148fb0e01 Mon Sep 17 00:00:00 2001 From: swiftyspiffy Date: Sun, 24 Dec 2023 13:58:05 -0900 Subject: [PATCH] implement Disposable (ported from #115) --- TwitchLib.PubSub/TwitchPubSub.cs | 37 +++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) 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); + } } }