From 8ef13b75266508f074c932d7eb608a504c4900a6 Mon Sep 17 00:00:00 2001 From: Mark Cilia Vincenti Date: Wed, 24 Jul 2024 04:23:36 +0200 Subject: [PATCH] Made the RandomHelper thread-safe. (#542) * Made the RandomHelper thread-safe. * Made the RandomHelper thread-safe. --- src/EasyCaching.Core/Internal/RandomHelper.cs | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/EasyCaching.Core/Internal/RandomHelper.cs b/src/EasyCaching.Core/Internal/RandomHelper.cs index 1976fd73..61dbce5b 100644 --- a/src/EasyCaching.Core/Internal/RandomHelper.cs +++ b/src/EasyCaching.Core/Internal/RandomHelper.cs @@ -1,20 +1,30 @@ namespace EasyCaching.Core.Internal { using System; + using System.Threading; public static class RandomHelper { -#if NETSTANDARD2_0 - private static readonly Random _random = new Random(); +#if NET6_0_OR_GREATER + private static Random Instance => Random.Shared; +#else + private static Random Instance => _local.Value; + + private static readonly Random _global = new Random(); + private static readonly ThreadLocal _local = new ThreadLocal(() => + { + int seed; + lock (_global) + { + seed = _global.Next(); + } + return new Random(seed); + }); #endif public static int GetNext(int min, int max) { -#if NET6_0_OR_GREATER - return Random.Shared.Next(min, max); -#else - return _random.Next(min, max); -#endif + return Instance.Next(min, max); } } }