Skip to content

Commit a1dbc01

Browse files
authored
Thread safe Random class (#560)
* Thread safe * fix init
1 parent 4bac32a commit a1dbc01

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

tests/Neo.VM.Tests/Helpers/RandomHelper.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
// modifications are permitted.
1111

1212
using System;
13+
using System.Threading;
1314

1415
namespace Neo.Test.Helpers;
1516

1617
public class RandomHelper
1718
{
1819
private const string _randchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
19-
private static readonly Random _rand = new();
20+
21+
private static readonly ThreadLocal<Random> _rand = new(() => new Random());
2022

2123
/// <summary>
2224
/// Get random buffer
@@ -26,7 +28,7 @@ public class RandomHelper
2628
public static byte[] RandBuffer(int length)
2729
{
2830
var buffer = new byte[length];
29-
_rand.NextBytes(buffer);
31+
_rand.Value.NextBytes(buffer);
3032
return buffer;
3133
}
3234

@@ -41,7 +43,7 @@ public static string RandString(int length)
4143

4244
for (int i = 0; i < stringChars.Length; i++)
4345
{
44-
stringChars[i] = _randchars[_rand.Next(_randchars.Length)];
46+
stringChars[i] = _randchars[_rand.Value.Next(_randchars.Length)];
4547
}
4648

4749
return new string(stringChars);

0 commit comments

Comments
 (0)