From e0fe9d9d0deed23f4beec1284e25d9bd9bf453d2 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 1 Apr 2021 19:51:21 +0100 Subject: [PATCH 1/2] Use Random.Shared Use the new .NET 6 Random.Shared static property where possible. See https://github.com/dotnet/runtime/pull/50297. --- .../Data/WeatherForecastService.cs | 5 ++--- .../Server/Data/WeatherForecastService.cs | 5 ++--- .../Controllers/WeatherForecastController.cs | 5 ++--- .../BlazingPizza.Server/Pages/Map.razor | 5 ++--- .../TestApp/Pages/TimerComponent.razor | 7 +++---- .../BasicTestApp/ReorderingFocusComponent.razor | 3 +-- .../src/KeyManagement/KeyRingProvider.cs | 7 ++++++- .../Routing/test/UnitTests/RouteCollectionTest.cs | 3 +-- .../src/UserManagerSpecificationTests.cs | 5 ++--- .../samples/HeaderPropagationSample/Startup.cs | 3 +-- .../HelperPerformanceBenchmark.cs | 3 +-- .../Data/WeatherForecastService.cs | 5 ++--- .../Controllers/WeatherForecastController.cs | 15 ++++++--------- .../Controllers/WeatherForecastController.cs | 15 ++++++--------- .../Controllers/WeatherForecastController.cs | 5 ++--- .../Controllers/WeatherForecastController.cs | 5 ++--- .../Controllers/WeatherForecastController.cs | 5 ++--- .../Common.FunctionalTests/AspNetCorePortTests.cs | 4 +--- .../RequestResponseTests.cs | 3 +-- .../Kestrel/shared/test/MockSystemClock.cs | 4 +--- src/Servers/Kestrel/stress/Program.cs | 2 +- .../Internal/Protocol/MemoryBufferWriterTests.cs | 2 +- .../Microbenchmarks/MessageParserBenchmark.cs | 5 ++--- src/SignalR/samples/JwtClientSample/Program.cs | 3 +-- .../MockSystemClock.cs | 4 +--- src/Testing/test/HttpClientSlimTest.cs | 4 ++++ 26 files changed, 56 insertions(+), 76 deletions(-) diff --git a/src/Components/Samples/BlazorServerApp/Data/WeatherForecastService.cs b/src/Components/Samples/BlazorServerApp/Data/WeatherForecastService.cs index bd889ec34638..53fb28b8b67a 100644 --- a/src/Components/Samples/BlazorServerApp/Data/WeatherForecastService.cs +++ b/src/Components/Samples/BlazorServerApp/Data/WeatherForecastService.cs @@ -13,12 +13,11 @@ public class WeatherForecastService public Task GetForecastAsync(DateTime startDate) { - var rng = new Random(); return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray()); } } diff --git a/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Data/WeatherForecastService.cs b/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Data/WeatherForecastService.cs index 12e5fbd1527f..f633536c03f3 100644 --- a/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Data/WeatherForecastService.cs +++ b/src/Components/WebAssembly/Samples/HostedBlazorWebassemblyApp/Server/Data/WeatherForecastService.cs @@ -15,12 +15,11 @@ public class WeatherForecastService : IWeatherForecastService public Task GetForecastAsync(DateTime startDate) { - var rng = new Random(); return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray()); } } diff --git a/src/Components/WebAssembly/testassets/Wasm.Authentication.Server/Controllers/WeatherForecastController.cs b/src/Components/WebAssembly/testassets/Wasm.Authentication.Server/Controllers/WeatherForecastController.cs index 9fefb88335c0..0bcf4f452ba8 100644 --- a/src/Components/WebAssembly/testassets/Wasm.Authentication.Server/Controllers/WeatherForecastController.cs +++ b/src/Components/WebAssembly/testassets/Wasm.Authentication.Server/Controllers/WeatherForecastController.cs @@ -28,12 +28,11 @@ public WeatherForecastController(ILogger logger) [HttpGet] public IEnumerable Get() { - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } diff --git a/src/Components/benchmarkapps/BlazingPizza.Server/Pages/Map.razor b/src/Components/benchmarkapps/BlazingPizza.Server/Pages/Map.razor index 913dec9bd29d..8083933ba32f 100644 --- a/src/Components/benchmarkapps/BlazingPizza.Server/Pages/Map.razor +++ b/src/Components/benchmarkapps/BlazingPizza.Server/Pages/Map.razor @@ -10,7 +10,6 @@ @functions { private int locX; private int locY; - private Random random = new Random(); private Timer timer; private string locString; @@ -18,8 +17,8 @@ { timer = new Timer(_ => { - locX = random.Next(1000); - locY = random.Next(1000); + locX = Random.Shared.Next(1000); + locY = Random.Shared.Next(1000); locString = $"{locX},{locY}"; InvokeAsync(() => StateHasChanged()); diff --git a/src/Components/benchmarkapps/Wasm.Performance/TestApp/Pages/TimerComponent.razor b/src/Components/benchmarkapps/Wasm.Performance/TestApp/Pages/TimerComponent.razor index c458a0328f66..158ede6ba4e8 100644 --- a/src/Components/benchmarkapps/Wasm.Performance/TestApp/Pages/TimerComponent.razor +++ b/src/Components/benchmarkapps/Wasm.Performance/TestApp/Pages/TimerComponent.razor @@ -7,7 +7,6 @@ @code { - Random random = new Random(); Timer timer; int red = 128; int green = 128; @@ -22,9 +21,9 @@ { InvokeAsync(() => { - red = random.Next(0, 256); - green = random.Next(0, 256); - blue = random.Next(0, 256); + red = Random.Shared.Next(0, 256); + green = Random.Shared.Next(0, 256); + blue = Random.Shared.Next(0, 256); StateHasChanged(); BenchmarkEvent.Send(JSRuntime, "Finished updating color"); }); diff --git a/src/Components/test/testassets/BasicTestApp/ReorderingFocusComponent.razor b/src/Components/test/testassets/BasicTestApp/ReorderingFocusComponent.razor index 6eed155f00c6..f0b50f04c10c 100644 --- a/src/Components/test/testassets/BasicTestApp/ReorderingFocusComponent.razor +++ b/src/Components/test/testassets/BasicTestApp/ReorderingFocusComponent.razor @@ -31,7 +31,6 @@ @code { - Random rng = new Random(); TodoItem[] todoItems = new[] { new TodoItem { Id = 1, Text = "First" }, @@ -43,7 +42,7 @@ void Shuffle() { - todoItems = todoItems.OrderBy(x => rng.Next()).ToArray(); + todoItems = todoItems.OrderBy(x => Random.Shared.Next()).ToArray(); } class TodoItem diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs index 8827193369ff..34a3b81c8118 100644 --- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs +++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs @@ -259,7 +259,12 @@ private static TimeSpan GetRefreshPeriodWithJitter(TimeSpan refreshPeriod) // hit a single repository simultaneously. For instance, if the refresh period is 1 hour, // we'll return a value in the vicinity of 48 - 60 minutes. We use the Random class since // we don't need a secure PRNG for this. - return TimeSpan.FromTicks((long)(refreshPeriod.Ticks * (1.0d - (new Random().NextDouble() / 5)))); +#if NET6_0_OR_GREATER + var random = Random.Shared; +#else + var random = new Random(); +#endif + return TimeSpan.FromTicks((long)(refreshPeriod.Ticks * (1.0d - (random.NextDouble() / 5)))); } private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) diff --git a/src/Http/Routing/test/UnitTests/RouteCollectionTest.cs b/src/Http/Routing/test/UnitTests/RouteCollectionTest.cs index c46e02ce5770..e5ab4035d1d2 100644 --- a/src/Http/Routing/test/UnitTests/RouteCollectionTest.cs +++ b/src/Http/Routing/test/UnitTests/RouteCollectionTest.cs @@ -512,8 +512,7 @@ private static RouteCollection GetRouteCollectionWithNamedRoutes(IEnumerable()); - var random = new Random(); - var email = "foo" + random.Next() + "@example.com"; - var newEmail = "bar" + random.Next() + "@example.com"; + var email = "foo" + Random.Shared.Next() + "@example.com"; + var newEmail = "bar" + Random.Shared.Next() + "@example.com"; var user = CreateTestUser(email: email); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, newEmail)); diff --git a/src/Middleware/HeaderPropagation/samples/HeaderPropagationSample/Startup.cs b/src/Middleware/HeaderPropagation/samples/HeaderPropagationSample/Startup.cs index 00138f6efe31..3fa6633652e5 100644 --- a/src/Middleware/HeaderPropagation/samples/HeaderPropagationSample/Startup.cs +++ b/src/Middleware/HeaderPropagation/samples/HeaderPropagationSample/Startup.cs @@ -111,11 +111,10 @@ private static StringValues GenerateBetaFeatureOptions() var threshold = 0.80; // 20% chance for each feature in beta. - var random = new Random(); var values = new List(); for (var i = 0; i < features.Length; i++) { - if (random.NextDouble() > threshold) + if (Random.Shared.NextDouble() > threshold) { values.Add(features[i]); } diff --git a/src/Mvc/perf/Microbenchmarks/Microsoft.AspNetCore.Mvc/HelperPerformanceBenchmark.cs b/src/Mvc/perf/Microbenchmarks/Microsoft.AspNetCore.Mvc/HelperPerformanceBenchmark.cs index 833eeca3cb5b..91609df592b9 100644 --- a/src/Mvc/perf/Microbenchmarks/Microsoft.AspNetCore.Mvc/HelperPerformanceBenchmark.cs +++ b/src/Mvc/perf/Microbenchmarks/Microsoft.AspNetCore.Mvc/HelperPerformanceBenchmark.cs @@ -34,7 +34,6 @@ namespace Microsoft.AspNetCore.Mvc.Microbenchmarks { public class HelperPerformanceBenchmark : RuntimePerformanceBenchmarkBase { - private Random _rand = new Random(); public HelperPerformanceBenchmark() : base( "~/Views/HelperTyped.cshtml", "~/Views/HelperDynamic.cshtml", @@ -45,6 +44,6 @@ public HelperPerformanceBenchmark() : base( { } - protected override object Model => _rand.Next().ToString(CultureInfo.InvariantCulture); + protected override object Model => Random.Shared.Next().ToString(CultureInfo.InvariantCulture); } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs index 0f5abf39abbb..5749009ea6d9 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs @@ -13,12 +13,11 @@ public class WeatherForecastService public Task GetForecastAsync(DateTime startDate) { - var rng = new Random(); return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray()); } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs index 3067df19f1f8..8e93ef94c129 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs @@ -69,12 +69,11 @@ public async Task> Get() throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } @@ -95,12 +94,11 @@ public async Task> Get() HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); var user = await _graphServiceClient.Me.Request().GetAsync(); - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } @@ -117,12 +115,11 @@ public IEnumerable Get() HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); #endif - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs index 2c725ae0a954..b17adf71737b 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs @@ -68,12 +68,11 @@ public async Task> Get() throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } @@ -94,12 +93,11 @@ public async Task> Get() HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); var user = await _graphServiceClient.Me.Request().GetAsync(); - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } @@ -116,12 +114,11 @@ public IEnumerable Get() HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); #endif - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } diff --git a/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/Angular-CSharp/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/Angular-CSharp/Controllers/WeatherForecastController.cs index 097eb584608c..3d6d8b4b4c3a 100644 --- a/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/Angular-CSharp/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/Angular-CSharp/Controllers/WeatherForecastController.cs @@ -32,12 +32,11 @@ public WeatherForecastController(ILogger logger) [HttpGet] public IEnumerable Get() { - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } diff --git a/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/React-CSharp/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/React-CSharp/Controllers/WeatherForecastController.cs index 097eb584608c..3d6d8b4b4c3a 100644 --- a/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/React-CSharp/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/React-CSharp/Controllers/WeatherForecastController.cs @@ -32,12 +32,11 @@ public WeatherForecastController(ILogger logger) [HttpGet] public IEnumerable Get() { - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } diff --git a/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/ReactRedux-CSharp/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/ReactRedux-CSharp/Controllers/WeatherForecastController.cs index 42f3485fc9b2..fad58738b21d 100644 --- a/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/ReactRedux-CSharp/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.Spa.ProjectTemplates/content/ReactRedux-CSharp/Controllers/WeatherForecastController.cs @@ -26,12 +26,11 @@ public WeatherForecastController(ILogger logger) [HttpGet] public IEnumerable Get() { - var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } diff --git a/src/Servers/IIS/IIS/test/Common.FunctionalTests/AspNetCorePortTests.cs b/src/Servers/IIS/IIS/test/Common.FunctionalTests/AspNetCorePortTests.cs index fe8af43b2c3f..65fbb15a791e 100644 --- a/src/Servers/IIS/IIS/test/Common.FunctionalTests/AspNetCorePortTests.cs +++ b/src/Servers/IIS/IIS/test/Common.FunctionalTests/AspNetCorePortTests.cs @@ -22,8 +22,6 @@ public class AspNetCorePortTests : IISFunctionalTestBase private const int _minPort = 1025; private const int _maxPort = 48000; - private static readonly Random _random = new Random(); - public AspNetCorePortTests(PublishedSitesFixture fixture) : base(fixture) { } @@ -144,7 +142,7 @@ private static int GetUnusedRandomPort() for (var i = 0; i < retries; i++) { - var port = _random.Next(_minPort, _maxPort); + var port = Random.Shared.Next(_minPort, _maxPort); using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { diff --git a/src/Servers/IIS/IIS/test/Common.FunctionalTests/RequestResponseTests.cs b/src/Servers/IIS/IIS/test/Common.FunctionalTests/RequestResponseTests.cs index 36864ddaf23d..43322dca7021 100644 --- a/src/Servers/IIS/IIS/test/Common.FunctionalTests/RequestResponseTests.cs +++ b/src/Servers/IIS/IIS/test/Common.FunctionalTests/RequestResponseTests.cs @@ -672,7 +672,6 @@ public async Task ClientDisconnectStress() { var maxRequestSize = 1000; var blockSize = 40; - var random = new Random(); async Task RunRequests() { using (var connection = _fixture.CreateTestConnection()) @@ -685,7 +684,7 @@ await connection.Send( "", ""); - var disconnectAfter = random.Next(maxRequestSize); + var disconnectAfter = Random.Shared.Next(maxRequestSize); var data = new byte[blockSize]; for (int i = 0; i < disconnectAfter / blockSize; i++) { diff --git a/src/Servers/Kestrel/shared/test/MockSystemClock.cs b/src/Servers/Kestrel/shared/test/MockSystemClock.cs index 61a3d6e12350..8b44aa008cb5 100644 --- a/src/Servers/Kestrel/shared/test/MockSystemClock.cs +++ b/src/Servers/Kestrel/shared/test/MockSystemClock.cs @@ -9,8 +9,6 @@ namespace Microsoft.AspNetCore.Testing { public class MockSystemClock : ISystemClock { - private static Random _random = new Random(); - private long _utcNowTicks; public MockSystemClock() @@ -41,7 +39,7 @@ public DateTimeOffset UtcNow private long NextLong(long minValue, long maxValue) { - return (long)(_random.NextDouble() * (maxValue - minValue) + minValue); + return (long)(Random.Shared.NextDouble() * (maxValue - minValue) + minValue); } } } diff --git a/src/Servers/Kestrel/stress/Program.cs b/src/Servers/Kestrel/stress/Program.cs index cba15c76ea4d..d078df4b6ec9 100644 --- a/src/Servers/Kestrel/stress/Program.cs +++ b/src/Servers/Kestrel/stress/Program.cs @@ -64,7 +64,7 @@ public static void Main(string[] args) logPath : cmdline.HasOption("-trace") ? cmdline.ValueForOption("-trace") : null, aspnetLog : cmdline.ValueForOption("-aspnetlog"), listOps : cmdline.ValueForOption("-listOps"), - seed : cmdline.ValueForOption("-seed") ?? new Random().Next()); + seed : cmdline.ValueForOption("-seed") ?? Random.Shared.Next()); } private static void Run(int concurrentRequests, int maxContentLength, Version[] httpVersions, int? connectionLifetime, int[] opIndices, string logPath, bool aspnetLog, bool listOps, int seed) diff --git a/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs b/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs index ded5c5cf63d2..bf167c924ce2 100644 --- a/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs +++ b/src/SignalR/common/SignalR.Common/test/Internal/Protocol/MemoryBufferWriterTests.cs @@ -405,7 +405,7 @@ public void GetMemoryAllocatesNewSegmentWhenInsufficientSpaceInCurrentSegment() using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize)) { var data = new byte[MinimumSegmentSize]; - new Random().NextBytes(data); + Random.Shared.NextBytes(data); // Write half the minimum segment size bufferWriter.Write(data.AsSpan(0, MinimumSegmentSize / 2)); diff --git a/src/SignalR/perf/Microbenchmarks/MessageParserBenchmark.cs b/src/SignalR/perf/Microbenchmarks/MessageParserBenchmark.cs index f08d29a6e6b0..a40e3f56a93e 100644 --- a/src/SignalR/perf/Microbenchmarks/MessageParserBenchmark.cs +++ b/src/SignalR/perf/Microbenchmarks/MessageParserBenchmark.cs @@ -11,7 +11,6 @@ namespace Microsoft.AspNetCore.SignalR.Microbenchmarks { public class MessageParserBenchmark { - private static readonly Random Random = new Random(); private byte[] _binaryInput; private byte[] _textInput; @@ -25,7 +24,7 @@ public class MessageParserBenchmark public void Setup() { var buffer = new byte[MessageLength]; - Random.NextBytes(buffer); + Random.Shared.NextBytes(buffer); var writer = MemoryBufferWriter.Get(); try { @@ -39,7 +38,7 @@ public void Setup() } buffer = new byte[MessageLength]; - Random.NextBytes(buffer); + Random.Shared.NextBytes(buffer); writer = MemoryBufferWriter.Get(); try { diff --git a/src/SignalR/samples/JwtClientSample/Program.cs b/src/SignalR/samples/JwtClientSample/Program.cs index 870dd0116f57..9c80563581a3 100644 --- a/src/SignalR/samples/JwtClientSample/Program.cs +++ b/src/SignalR/samples/JwtClientSample/Program.cs @@ -24,7 +24,6 @@ await Task.WhenAll( private const string ServerUrl = "http://localhost:54543"; private readonly ConcurrentDictionary> _tokens = new ConcurrentDictionary>(StringComparer.Ordinal); - private readonly Random _random = new Random(); private async Task RunConnection(HttpTransportType transportType) { @@ -72,7 +71,7 @@ private async Task RunConnection(HttpTransportType transportType) if (ticks % nextMsgAt == 0) { await hubConnection.SendAsync("Broadcast", userId, $"Hello at {DateTime.Now}"); - nextMsgAt = _random.Next(2, 5); + nextMsgAt = Random.Shared.Next(2, 5); } } } diff --git a/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/MockSystemClock.cs b/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/MockSystemClock.cs index 2cd2eb617d52..b4fac68d526f 100644 --- a/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/MockSystemClock.cs +++ b/src/SignalR/server/SignalR/test/HubConnectionHandlerTestUtils/MockSystemClock.cs @@ -9,8 +9,6 @@ namespace Microsoft.AspNetCore.SignalR.Tests { public class MockSystemClock : ISystemClock { - private static Random _random = new Random(); - private long _utcNowTicks; public MockSystemClock() @@ -41,7 +39,7 @@ public DateTimeOffset UtcNow private long NextLong(long minValue, long maxValue) { - return (long)(_random.NextDouble() * (maxValue - minValue) + minValue); + return (long)(Random.Shared.NextDouble() * (maxValue - minValue) + minValue); } } } diff --git a/src/Testing/test/HttpClientSlimTest.cs b/src/Testing/test/HttpClientSlimTest.cs index ede48243e5ab..5cda1c46c3af 100644 --- a/src/Testing/test/HttpClientSlimTest.cs +++ b/src/Testing/test/HttpClientSlimTest.cs @@ -68,7 +68,11 @@ public void GetHostExcludesDefaultPort() private HttpListener StartHost(out string address, int statusCode = 200, Func handler = null) { var listener = new HttpListener(); +#if NET6_0_OR_GREATER + var random = Random.Shared; +#else var random = new Random(); +#endif address = null; for (var i = 0; i < 10; i++) From e0e6fee60749261d1b8642057ccbb1015bdddc82 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 1 Apr 2021 21:09:53 +0100 Subject: [PATCH 2/2] Revert WebApi-CSharp changes For some reason I don't understand, this template doesn't see Random.Shared when compiled so this reverts the previous change for this template. --- .../Controllers/WeatherForecastController.cs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs index b17adf71737b..2c725ae0a954 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs @@ -68,11 +68,12 @@ public async Task> Get() throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } + var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } @@ -93,11 +94,12 @@ public async Task> Get() HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); var user = await _graphServiceClient.Me.Request().GetAsync(); + var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } @@ -114,11 +116,12 @@ public IEnumerable Get() HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); #endif + var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] + TemperatureC = rng.Next(-20, 55), + Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); }