如何在ASP.Net上的异步操作中运行线程安全的随机数?

时间:2017-06-23 10:29:44

标签: c# asp.net asynchronous random thread-safety

如何在异步操作中运行线程安全的随机数?

它总是返回零。我试图在startup.cs中创建一个实例,它设置当前的静态电流,但它仍然总是返回零。

我正在使用ASP.Net Core。

public class SafeRandom
{
    public static SafeRandom Instance { get; private set; }

    public SafeRandom()
    {
        Instance = this;
    }

    private readonly static Random _global = new Random();
    [ThreadStatic]
    private Random _local;

    public int Next(int min,int max)
    {
        Random inst = _local;
        if (inst == null)
        {
            int seed;
            lock (_global) seed = _global.Next();
            _local = inst = new Random(seed);
        }
        return inst.Next(min,max);
    }
}

在Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();

        //new SafeRandom(); (tried)
        services.AddInstance<SafeRandom>(new SafeRandom());

    }

1 个答案:

答案 0 :(得分:0)

没关系我让它上班了。 我把我的代码更改为了这个并且我在我的结尾处发生了一个重大错误,其中Next(0,1)应该是(0,2)返回0-1;

public class SafeRandom
{
    public static SafeRandom Instance { get; private set; }

    public SafeRandom()
    {
        Instance = this;
    }

    [ThreadStatic]
    private RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();

    // Return a random integer between a min and max value.
    public int Next(int min, int max)
    {
        uint scale = uint.MaxValue;
        while (scale == uint.MaxValue)
        {
            // Get four random bytes.
            byte[] four_bytes = new byte[4];
            provider.GetBytes(four_bytes);

            // Convert that into an uint.
            scale = BitConverter.ToUInt32(four_bytes, 0);
        }

        // Add min to the scaled difference between max and min.
        return (int)(min + (max - min) *
            (scale / (double)uint.MaxValue));
    }
}