Skip to content

Commit

Permalink
Made the RandomHelper thread-safe. (#542)
Browse files Browse the repository at this point in the history
* Made the RandomHelper thread-safe.

* Made the RandomHelper thread-safe.
  • Loading branch information
MarkCiliaVincenti authored Jul 24, 2024
1 parent 48709f8 commit 8ef13b7
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/EasyCaching.Core/Internal/RandomHelper.cs
Original file line number Diff line number Diff line change
@@ -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<Random> _local = new ThreadLocal<Random>(() =>
{
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);
}
}
}

0 comments on commit 8ef13b7

Please sign in to comment.