mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
[core] add thread safe random to DI
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user