Changed various locking mechanisms.

This commit is contained in:
Tom
2025-03-29 20:28:36 +00:00
parent eddd9e6403
commit fb04f4003f
11 changed files with 272 additions and 155 deletions

View File

@@ -18,21 +18,22 @@ namespace TwitchChatTTS.Twitch.Socket
private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
private readonly object _lock;
private readonly Mutex _mutex;
public TwitchConnectionManager(IServiceProvider serviceProvider, ILogger logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
_lock = new object();
_mutex = new Mutex();
}
public TwitchWebsocketClient GetBackupClient()
{
lock (_lock)
try
{
_mutex.WaitOne();
if (_identified == null)
throw new InvalidOperationException("Cannot get backup Twitch client yet. Waiting for identification.");
if (_backup != null)
@@ -40,12 +41,17 @@ namespace TwitchChatTTS.Twitch.Socket
return CreateNewClient();
}
finally
{
_mutex.ReleaseMutex();
}
}
public TwitchWebsocketClient GetWorkingClient()
{
lock (_lock)
try
{
_mutex.WaitOne();
if (_identified == null)
{
return CreateNewClient();
@@ -53,6 +59,10 @@ namespace TwitchChatTTS.Twitch.Socket
return _identified;
}
finally
{
_mutex.ReleaseMutex();
}
}
private TwitchWebsocketClient CreateNewClient()
@@ -74,8 +84,9 @@ namespace TwitchChatTTS.Twitch.Socket
private async Task OnDisconnection(TwitchWebsocketClient client)
{
bool reconnecting = false;
lock (_lock)
try
{
_mutex.WaitOne();
if (_identified?.UID == client.UID)
{
_logger.Debug($"Identified Twitch client has disconnected [client: {client.UID}][main: {_identified.UID}][backup: {_backup?.UID}]");
@@ -92,19 +103,25 @@ namespace TwitchChatTTS.Twitch.Socket
else
_logger.Warning($"Twitch client disconnected from unknown source [client: {client.UID}][main: {_identified?.UID}][backup: {_backup?.UID}]");
}
finally
{
_mutex.ReleaseMutex();
}
if (reconnecting)
{
var newClient = GetWorkingClient();
await newClient.Reconnect();
}
}
private async Task OnIdentified(TwitchWebsocketClient client)
{
bool clientDisconnect = false;
lock (_lock)
try
{
_mutex.WaitOne();
if (_identified == null || _identified.ReceivedReconnecting)
{
if (_backup != null && _backup.UID == client.UID)
@@ -125,10 +142,14 @@ namespace TwitchChatTTS.Twitch.Socket
_logger.Warning($"Twitch client has been identified, but isn't main or backup [client: {client.UID}][main: {_identified.UID}][backup: {_backup?.UID}]");
clientDisconnect = true;
}
}
if (clientDisconnect)
await client.DisconnectAsync(new SocketDisconnectionEventArgs("Closed", "No need for a tertiary client."));
if (clientDisconnect)
client.DisconnectAsync(new SocketDisconnectionEventArgs("Closed", "No need for a tertiary client.")).Wait();
}
finally
{
_mutex.ReleaseMutex();
}
}
}
}