From 98b1e2f0f7847ddaf85e7a78e8ed45f13d702209 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Tue, 17 Jan 2023 22:42:48 +0200 Subject: [PATCH] [core] add thread safe random to DI --- Core/Startup.cs | 2 ++ Core/ThreadSafeRandom.cs | 43 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 Core/ThreadSafeRandom.cs diff --git a/Core/Startup.cs b/Core/Startup.cs index cee6101..f0507c0 100644 --- a/Core/Startup.cs +++ b/Core/Startup.cs @@ -45,6 +45,8 @@ namespace Kruzya.TelegramBot.Core services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + // Trigger module handlers. _core.Modules.ConfigureServices(services); } diff --git a/Core/ThreadSafeRandom.cs b/Core/ThreadSafeRandom.cs new file mode 100644 index 0000000..d5cef48 --- /dev/null +++ b/Core/ThreadSafeRandom.cs @@ -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); + } + } +} \ No newline at end of file