Last active
November 13, 2020 16:41
-
-
Save aaronhoffman/f40bef2954b6e5705adc0885e5584ae3 to your computer and use it in GitHub Desktop.
Thread safe way to use MS Random in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
adopted from https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/