Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Random.Shared property #31453

Merged
2 commits merged into from
Apr 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ public class WeatherForecastService

public Task<WeatherForecast[]> 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());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@ public class WeatherForecastService : IWeatherForecastService

public Task<WeatherForecast[]> 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());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,11 @@ public WeatherForecastController(ILogger<WeatherForecastController> logger)
[HttpGet]
public IEnumerable<WeatherForecast> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,15 @@
@functions {
private int locX;
private int locY;
private Random random = new Random();
private Timer timer;
private string locString;

protected override void OnInitialized()
{
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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

@code
{
Random random = new Random();
Timer timer;
int red = 128;
int green = 128;
Expand All @@ -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");
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
</ul>

@code {
Random rng = new Random();
TodoItem[] todoItems = new[]
{
new TodoItem { Id = 1, Text = "First" },
Expand All @@ -43,7 +42,7 @@

void Shuffle()
{
todoItems = todoItems.OrderBy(x => rng.Next()).ToArray();
todoItems = todoItems.OrderBy(x => Random.Shared.Next()).ToArray();
}

class TodoItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions src/Http/Routing/test/UnitTests/RouteCollectionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -512,8 +512,7 @@ private static RouteCollection GetRouteCollectionWithNamedRoutes(IEnumerable<str

private static RouteCollection GetNestedRouteCollection(string[] routeNames)
{
var random = new Random();
int index = random.Next(0, routeNames.Length - 1);
int index = Random.Shared.Next(0, routeNames.Length - 1);
var first = routeNames.Take(index).ToArray();
var second = routeNames.Skip(index).ToArray();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,9 +305,8 @@ public async Task CheckSetEmailValidatesUser()
var manager = CreateManager();
manager.Options.User.RequireUniqueEmail = true;
manager.UserValidators.Add(new UserValidator<TUser>());
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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
for (var i = 0; i < features.Length; i++)
{
if (random.NextDouble() > threshold)
if (Random.Shared.NextDouble() > threshold)
{
values.Add(features[i]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ public class WeatherForecastService

public Task<WeatherForecast[]> 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());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,11 @@ public async Task<IEnumerable<WeatherForecast>> 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();
}
Expand All @@ -95,12 +94,11 @@ public async Task<IEnumerable<WeatherForecast>> 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();
}
Expand All @@ -117,12 +115,11 @@ public IEnumerable<WeatherForecast> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,11 @@ public WeatherForecastController(ILogger<WeatherForecastController> logger)
[HttpGet]
public IEnumerable<WeatherForecast> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,11 @@ public WeatherForecastController(ILogger<WeatherForecastController> logger)
[HttpGet]
public IEnumerable<WeatherForecast> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@ public WeatherForecastController(ILogger<WeatherForecastController> logger)
[HttpGet]
public IEnumerable<WeatherForecast> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
}
Expand Down Expand Up @@ -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))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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++)
{
Expand Down
4 changes: 1 addition & 3 deletions src/Servers/Kestrel/shared/test/MockSystemClock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ namespace Microsoft.AspNetCore.Testing
{
public class MockSystemClock : ISystemClock
{
private static Random _random = new Random();

private long _utcNowTicks;

public MockSystemClock()
Expand Down Expand Up @@ -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);
}
}
}
2 changes: 1 addition & 1 deletion src/Servers/Kestrel/stress/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static void Main(string[] args)
logPath : cmdline.HasOption("-trace") ? cmdline.ValueForOption<string>("-trace") : null,
aspnetLog : cmdline.ValueForOption<bool>("-aspnetlog"),
listOps : cmdline.ValueForOption<bool>("-listOps"),
seed : cmdline.ValueForOption<int?>("-seed") ?? new Random().Next());
seed : cmdline.ValueForOption<int?>("-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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
5 changes: 2 additions & 3 deletions src/SignalR/perf/Microbenchmarks/MessageParserBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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
{
Expand All @@ -39,7 +38,7 @@ public void Setup()
}

buffer = new byte[MessageLength];
Random.NextBytes(buffer);
Random.Shared.NextBytes(buffer);
writer = MemoryBufferWriter.Get();
try
{
Expand Down
3 changes: 1 addition & 2 deletions src/SignalR/samples/JwtClientSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ await Task.WhenAll(
private const string ServerUrl = "http://localhost:54543";

private readonly ConcurrentDictionary<string, Task<string>> _tokens = new ConcurrentDictionary<string, Task<string>>(StringComparer.Ordinal);
private readonly Random _random = new Random();

private async Task RunConnection(HttpTransportType transportType)
{
Expand Down Expand Up @@ -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);
}
}
}
Expand Down
Loading