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

@ -9,25 +9,28 @@ namespace TwitchChatTTS.Seven.Socket.Handlers
{
public class DispatchHandler : IWebSocketHandler
{
public int OperationCode { get; } = 0;
private readonly ILogger _logger;
private readonly IEmoteDatabase _emotes;
private readonly object _lock = new object();
public int OperationCode { get; } = 0;
private readonly Mutex _lock;
public DispatchHandler(IEmoteDatabase emotes, ILogger logger)
{
_emotes = emotes;
_logger = logger;
_lock = new Mutex();
}
public Task Execute<Data>(SocketClient<WebSocketMessage> sender, Data data)
{
if (data is not DispatchMessage message || message == null)
if (data is not DispatchMessage message || message == null || message.Body == null)
return Task.CompletedTask;
ApplyChanges(message?.Body?.Pulled, cf => cf.OldValue, true);
ApplyChanges(message?.Body?.Pushed, cf => cf.Value, false);
ApplyChanges(message?.Body?.Removed, cf => cf.OldValue, true);
ApplyChanges(message?.Body?.Updated, cf => cf.OldValue, false, cf => cf.Value);
ApplyChanges(message.Body.Pulled, cf => cf.OldValue, true);
ApplyChanges(message.Body.Pushed, cf => cf.Value, false);
ApplyChanges(message.Body.Removed, cf => cf.OldValue, true);
ApplyChanges(message.Body.Updated, cf => cf.OldValue, false, cf => cf.Value);
return Task.CompletedTask;
}
@ -42,7 +45,7 @@ namespace TwitchChatTTS.Seven.Socket.Handlers
if (value == null)
continue;
var o = JsonSerializer.Deserialize<EmoteField>(value.ToString(), new JsonSerializerOptions()
var o = JsonSerializer.Deserialize<EmoteField>(value.ToString()!, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = false,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
@ -50,8 +53,9 @@ namespace TwitchChatTTS.Seven.Socket.Handlers
if (o == null)
continue;
lock (_lock)
try
{
_lock.WaitOne();
if (removing)
{
if (_emotes.Get(o.Name) != o.Id)
@ -71,8 +75,10 @@ namespace TwitchChatTTS.Seven.Socket.Handlers
}
_emotes.Remove(o.Name);
var update = updater(val);
if (update == null)
continue;
var u = JsonSerializer.Deserialize<EmoteField>(update.ToString(), new JsonSerializerOptions()
var u = JsonSerializer.Deserialize<EmoteField>(update.ToString()!, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = false,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
@ -94,6 +100,10 @@ namespace TwitchChatTTS.Seven.Socket.Handlers
_logger.Information($"Added 7tv emote [name: {o.Name}][id: {o.Id}]");
}
}
finally
{
_lock.ReleaseMutex();
}
}
}
}

View File

@ -1,4 +1,3 @@
using System.Net.WebSockets;
using CommonSocketLibrary.Abstract;
using CommonSocketLibrary.Common;
using TwitchChatTTS.Seven.Socket.Data;