Skip to content

Commit

Permalink
Use a thread safe Random instance #944
Browse files Browse the repository at this point in the history
  • Loading branch information
watfordsuzy committed Apr 11, 2024
1 parent 826f844 commit 4b48d08
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Box.V2/Utility/ExponentialBackoff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ namespace Box.V2.Utility
{
public class ExponentialBackoff : IRetryStrategy
{
private readonly Random _random = new Random();

public TimeSpan GetRetryTimeout(int numRetries)
{
var baseInterval = TimeSpan.FromSeconds(2.0);
const double RETRY_RANDOMIZATION_FACTOR = 0.5;
var minRandomization = 1 - RETRY_RANDOMIZATION_FACTOR;
var maxRandomization = 1 + RETRY_RANDOMIZATION_FACTOR;

var randomization = _random.NextDouble() * (maxRandomization - minRandomization) + minRandomization;
var randomization = ThreadSafeRandom.Instance.NextDouble()

Check failure on line 14 in Box.V2/Utility/ExponentialBackoff.cs

View workflow job for this annotation

GitHub Actions / Build and Test - Framework

The name 'ThreadSafeRandom' does not exist in the current context
* (maxRandomization - minRandomization) + minRandomization;

var exponential = Math.Pow(2, numRetries - 1);
var result = Math.Ceiling(exponential * baseInterval.TotalSeconds * randomization);
return TimeSpan.FromSeconds(result);
Expand Down
37 changes: 37 additions & 0 deletions Box.V2/Utility/ThreadSafeRandom.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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, .NET Standard, and .NET 6+.
/// </summary>
/// <seealso href="https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-random"/>
internal static class ThreadSafeRandom
{
#if NET6_0_OR_GREATER
/// <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.Shared;
#else
//
// Adapted from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Random.cs
//

[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();
#endif
}
}

0 comments on commit 4b48d08

Please sign in to comment.