-
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.
fix: do not recreate Random each time (#945)
* fix: do not recreate Random each time On .NET Framework it is incorrect to recreate Random instances each time, these should instead be one per instance. On .NET Core and later this is not a limitation, but the libraries share a codebase. Fixes #944 * Use a thread safe Random instance #944 * Forgot to commit csproj change #944 * Address PR comment #944
- Loading branch information
1 parent
b410dfd
commit d03b1ce
Showing
3 changed files
with
36 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
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,31 @@ | ||
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 and .NET Standard. | ||
/// </summary> | ||
/// <seealso href="https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-random"/> | ||
internal static class ThreadSafeRandom | ||
{ | ||
// | ||
// Adapted from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Random.cs | ||
// | ||
// NOTE: when/if this library updates to .NET 6+, this code can be replaced with `Random.Shared` | ||
// | ||
|
||
[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(); | ||
} | ||
} |