Dispose of Shuffle properly before rebuilding it as otherwise you end up with random Shuffle ping tasks waking up and trying to ping a dead connection

This commit is contained in:
barelyprofessional
2024-06-27 11:15:41 +08:00
parent 5bff1a1035
commit 4ece07d64d
2 changed files with 11 additions and 2 deletions

View File

@@ -114,6 +114,7 @@ public class KickBot
{ {
if (e.Type == DisconnectionType.ByServer) if (e.Type == DisconnectionType.ByServer)
{ {
_shuffle.Dispose();
BuildShuffle(); BuildShuffle();
} }
} }

View File

@@ -8,7 +8,7 @@ using Websocket.Client;
namespace KfChatDotNetKickBot.Services; namespace KfChatDotNetKickBot.Services;
public class Shuffle public class Shuffle : IDisposable
{ {
private Logger _logger = LogManager.GetCurrentClassLogger(); private Logger _logger = LogManager.GetCurrentClassLogger();
private WebsocketClient _wsClient; private WebsocketClient _wsClient;
@@ -20,6 +20,7 @@ public class Shuffle
public event OnLatestBetUpdatedEventHandler OnLatestBetUpdated; public event OnLatestBetUpdatedEventHandler OnLatestBetUpdated;
public event OnWsDisconnectionEventHandler OnWsDisconnection; public event OnWsDisconnectionEventHandler OnWsDisconnection;
private CancellationToken _cancellationToken = CancellationToken.None; private CancellationToken _cancellationToken = CancellationToken.None;
private CancellationTokenSource _pingCts = new();
public Shuffle(string? proxy = null, CancellationToken? cancellationToken = null) public Shuffle(string? proxy = null, CancellationToken? cancellationToken = null)
{ {
@@ -79,7 +80,7 @@ public class Shuffle
private async Task PeriodicPing() private async Task PeriodicPing()
{ {
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10)); using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(_cancellationToken)) while (await timer.WaitForNextTickAsync(_pingCts.Token))
{ {
if (_wsClient == null) if (_wsClient == null)
{ {
@@ -217,4 +218,11 @@ public class Shuffle
} }
public class ShuffleUserNotFoundException : Exception; public class ShuffleUserNotFoundException : Exception;
public void Dispose()
{
_pingCts.Cancel();
_wsClient.Dispose();
GC.SuppressFinalize(this);
}
} }