简体   繁体   English

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

[英]How do I run thread-safe random numbers in async actions on ASP.Net?

How do I run thread-safe random numbers in async actions? 如何在异步操作中运行线程安全随机数?

It always return zero. 它总是返回零。 I tried to to make a instance in startup.cs which set a static istance of the current but it still always return zero. 我试图在startup.cs中创建一个实例,该实例设置了当前的静态距离,但它始终始终返回零。

I am using ASP.Net Core. 我正在使用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);
    }
}

In Startup.cs 在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());

    }

Nevermind I got it to work. 没关系,我让它正常工作。 I changed my code to this and I also made a major error on my end where Next(0,1) should had been (0,2) to return 0-1; 我将代码更改为此,并在端部也犯了一个重大错误,其中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));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM