Monday, May 23, 2016

C# Random repeating issue - solution

using System;
using System.Threading;

namespace SubProj
{
    public static class RandomProvider
    {
        private static int seed = Environment.TickCount;

        private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>
            (() => new Random(Interlocked.Increment(ref seed)));

        public static Random GetThreadRandom()
        {
            return randomWrapper.Value;
        }
    }
}


calling:

private string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            var random = RandomProvider.GetThreadRandom();
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        private string RandomBoolean()
        {
            string[] strData = { "true", "false" };
            Random r = RandomProvider.GetThreadRandom();
            int index = r.Next(strData.Length);
            return strData[index];
        }

        private string RandomInt(int length)
        {
            const string chars = "0123456789";
            var random = RandomProvider.GetThreadRandom();
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

No comments:

Post a Comment

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...