-
Notifications
You must be signed in to change notification settings - Fork 163
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use a thread safe Random instance #944
- Loading branch information
1 parent
826f844
commit 4b48d08
Showing
2 changed files
with
40 additions
and
3 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
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 |
---|---|---|
@@ -0,0 +1,37 @@ | ||
using System; | ||
using System.Runtime.CompilerServices; | ||
|
||
namespace Box.V2.Utility | ||
{ | ||
/// <summary> | ||
/// A thread safe implementation of <see cref="Random"/>, following best practices | ||
/// for .NET Framework, .NET Standard, and .NET 6+. | ||
/// </summary> | ||
/// <seealso href="https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-random"/> | ||
internal static class ThreadSafeRandom | ||
{ | ||
#if NET6_0_OR_GREATER | ||
/// <summary> | ||
/// An instance of <see cref="Random"/> specific to the calling thread. | ||
/// Do not pass this instance to other threads or contexts. | ||
/// </summary> | ||
public static Random Instance => Random.Shared; | ||
#else | ||
// | ||
// Adapted from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Random.cs | ||
// | ||
|
||
[ThreadStatic] | ||
private static Random _random; | ||
|
||
[MethodImpl(MethodImplOptions.NoInlining)] | ||
private static Random CreateRandom() => _random = new Random(); | ||
|
||
/// <summary> | ||
/// An instance of <see cref="Random"/> specific to the calling thread. | ||
/// Do not pass this instance to other threads or contexts. | ||
/// </summary> | ||
public static Random Instance => _random ?? CreateRandom(); | ||
#endif | ||
} | ||
} |