Add sync primitives to singletons' operations

This commit is contained in:
Sergey Nazarov 2024-03-20 19:55:33 +04:00
parent f2b4864237
commit e9cf1bd814
3 changed files with 37 additions and 21 deletions

View File

@ -12,6 +12,8 @@ public sealed class TelegramClientContainer : ITelegramClientContainer, IDisposa
public bool Initialized { get; private set; }
private readonly object _syncRoot = new();
public TelegramClientContainer(IOptions<WTelegramClientOptions> options)
{
_options = options.Value ?? throw new ArgumentNullException(nameof(options));
@ -19,19 +21,25 @@ public sealed class TelegramClientContainer : ITelegramClientContainer, IDisposa
public void Initialize()
{
if (Initialized)
return;
lock (_syncRoot)
{
if (Initialized)
return;
_client = new Client(ConfigureWTelegramClient);
_client = new Client(ConfigureWTelegramClient);
Initialized = true;
Initialized = true;
}
}
public void Reset()
{
Initialized = false;
Dispose();
_client = null;
lock (_syncRoot)
{
Initialized = false;
Dispose();
_client = null;
}
}
private string ConfigureWTelegramClient(string what)

View File

@ -9,26 +9,35 @@ public sealed class TelegramRegistry
public ConcurrentDictionary<long, User> Users = new();
public ConcurrentDictionary<long, ChatBase> Chats = new();
private readonly object _syncRoot = new();
public void SetMy(User my)
{
if (my == null)
lock (_syncRoot)
{
throw new ArgumentNullException(nameof(my));
}
if (My == null)
{
My = my;
return;
}
if (my == null)
{
throw new ArgumentNullException(nameof(my));
}
throw new InvalidOperationException("My already set");
if (My == null)
{
My = my;
Users[my.id] = my;
return;
}
throw new InvalidOperationException("My already set");
}
}
public void Clear()
{
My = null;
Users.Clear();
Chats.Clear();
lock (_syncRoot)
{
My = null;
Users.Clear();
Chats.Clear();
}
}
}

View File

@ -47,7 +47,6 @@ public sealed class UpdateListenerBackgroundService : BackgroundService
client.OnUpdate += HandleUpdates;
var my = await client.LoginUserIfNeeded();
_telegramRegistry.SetMy(my);
_telegramRegistry.Users[my.id] = my;
// Note: on login, Telegram may sends a bunch of updates/messages that happened in the past and were not acknowledged
Console.WriteLine(