Skip to content

Instantly share code, notes, and snippets.

@aaronhoffman
Last active November 13, 2020 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronhoffman/f40bef2954b6e5705adc0885e5584ae3 to your computer and use it in GitHub Desktop.
Save aaronhoffman/f40bef2954b6e5705adc0885e5584ae3 to your computer and use it in GitHub Desktop.
Thread safe way to use MS Random in C#
public interface IRandomFactory
{
Random CreateOrRetrieve();
}
public class RandomFactory : IRandomFactory
{
public Random CreateOrRetrieve()
{
return _threadLocalRandom.Value;
}
private static Random NewThreadLocalRandom()
{
lock (_globalLock)
{
return new Random(_globalRandom.Next());
}
}
private static readonly Random _globalRandom = new Random();
private static readonly object _globalLock = new object();
private static ThreadLocal<Random> _threadLocalRandom = new ThreadLocal<Random>(NewThreadLocalRandom);
}
@aaronhoffman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment