Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made the RandomHelper thread-safe. #542

Merged
merged 2 commits into from
Jul 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}
Loading