-
Notifications
You must be signed in to change notification settings - Fork 322
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Made the RandomHelper thread-safe. (#542)
* Made the RandomHelper thread-safe. * Made the RandomHelper thread-safe.
- Loading branch information
1 parent
48709f8
commit 8ef13b7
Showing
1 changed file
with
17 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |