| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="RandomGenerator.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using System.Threading; |
| | | 10 | | |
| | | 11 | | namespace MyNet.Generator.Facade; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Provides a thread-safe and lock-free random number generator instance. |
| | | 15 | | /// </summary> |
| | | 16 | | [SuppressMessage("Security", "CA5394:Do not use insecure randomness", Justification = "Using System.Random.Shared for no |
| | | 17 | | public static class RandomGenerator |
| | | 18 | | { |
| | 5 | 19 | | private static IRandomGenerator _current = new DefaultRandomGenerator(new SystemRandomSource()); |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Gets or sets the service used by static Random* helpers. |
| | | 23 | | /// </summary> |
| | | 24 | | public static IRandomGenerator Current |
| | | 25 | | { |
| | 6827 | 26 | | get => Volatile.Read(ref _current); |
| | 12 | 27 | | set => Volatile.Write(ref _current, |
| | 12 | 28 | | value ?? throw new ArgumentNullException(nameof(value))); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Gets the underlying shared random instance. |
| | | 33 | | /// </summary> |
| | 0 | 34 | | public static Random Instance => Random.Shared; |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Resets static random helpers to the default service implementation. |
| | | 38 | | /// </summary> |
| | 3 | 39 | | public static void Reset() => Volatile.Write( |
| | 3 | 40 | | ref _current, |
| | 3 | 41 | | new DefaultRandomGenerator(new SystemRandomSource())); |
| | | 42 | | } |
| | | 43 | | |