From 849dbfc2f6cda256a74a3adc4e0e429d988f325d Mon Sep 17 00:00:00 2001 From: KennethKo <31635054+KennethKo@users.noreply.github.com> Date: Mon, 7 Aug 2023 19:28:32 -0700 Subject: [PATCH] localLocker for localSeed Randomizer currently locks a global lock to protect local seeds. The Locker was never updated when localSeed was introduced. --- Source/Bogus/Randomizer.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Source/Bogus/Randomizer.cs b/Source/Bogus/Randomizer.cs index 76fe7c5c..6baf1b37 100644 --- a/Source/Bogus/Randomizer.cs +++ b/Source/Bogus/Randomizer.cs @@ -30,6 +30,7 @@ public class Randomizer public Randomizer() { this.localSeed = Seed; + this.localLocker = Locker; } /// @@ -39,12 +40,15 @@ public Randomizer() public Randomizer(int localSeed) { this.localSeed = new Random(localSeed); + this.localLocker = new Lazy(() => new object(), LazyThreadSafetyMode.ExecutionAndPublication); } /// /// The pseudo-random number generator that is used for all random number generation in this instance. /// protected Random localSeed; + + internal Lazy localLocker; /// /// Get an int from 0 to max. @@ -82,7 +86,7 @@ public int[] Digits(int count, int minDigit = 0, int maxDigit = 9) public int Number(int min = 0, int max = 1) { //lock any seed access, for thread safety. - lock( Locker.Value ) + lock( localLocker.Value ) { // Adjust the range as needed to make max inclusive. The Random.Next function uses exclusive upper bounds. @@ -178,7 +182,7 @@ public int Odd(int min = 0, int max = 1) public double Double(double min = 0.0d, double max = 1.0d) { //lock any seed access, for thread safety. - lock( Locker.Value ) + lock( localLocker.Value ) { if( min == 0.0d && max == 1.0d ) { @@ -227,7 +231,7 @@ public byte Byte(byte min = byte.MinValue, byte max = byte.MaxValue) public byte[] Bytes(int count) { var arr = new byte[count]; - lock( Locker.Value ) + lock( localLocker.Value ) { localSeed.NextBytes(arr); } @@ -720,7 +724,7 @@ public IEnumerable Shuffle(IEnumerable source) { int j; //lock any seed access, for thread safety. - lock( Locker.Value ) + lock( localLocker.Value ) { j = this.localSeed.Next(i, buffer.Count); }