[core] add thread safe random to DI

This commit is contained in:
Andriy
2023-01-17 22:42:48 +02:00
parent 55a4569a4a
commit 98b1e2f0f7
2 changed files with 45 additions and 0 deletions
+2
View File
@@ -45,6 +45,8 @@ namespace Kruzya.TelegramBot.Core
services.AddSingleton<UserService>();
services.AddSingleton<IAntiFlood, MemoryAntiFloodService>();
services.AddSingleton<ThreadSafeRandom>();
// Trigger module handlers.
_core.Modules.ConfigureServices(services);
}
+43
View File
@@ -0,0 +1,43 @@
using System;
namespace Kruzya.TelegramBot.Core;
public class ThreadSafeRandom
{
private static readonly Random Global = new();
[ThreadStatic] private static Random _local;
public int Next()
{
CheckLocal();
return _local.Next();
}
public int Next(int minValue, int maxValue)
{
CheckLocal();
return _local.Next(minValue, maxValue);
}
public int Next(int maxValue)
{
CheckLocal();
return _local.Next(maxValue);
}
private static void CheckLocal()
{
if (_local == null)
{
int seed;
lock (Global)
{
seed = Global.Next();
}
_local = new Random(seed);
}
}
}