小编Ale*_*kov的帖子

以线程安全的方式获取随机数

这是一篇很好的文章,描述了随机数的线程安全性:以线程安全的方式获取随机数

但我坚持使用"RandomGen2"示例:

public static class RandomGen2 
{ 
    private static Random _global = new Random(); 
    [ThreadStatic] 
    private static Random _local;

    public static int Next() 
    { 
       Random inst = _local; 
       if (inst == null) 
       { 
           int seed; 
           lock (_global) seed = _global.Next(); 
           _local = inst = new Random(seed); 
       } 
       return inst.Next(); 
   } 
Run Code Online (Sandbox Code Playgroud)

}

为什么线程静态字段被复制到局部变量:Random inst = _local; ?为什么不简单地使用

if (_local == null) .... return _local.Next()

.net c# random multithreading thread-safety

7
推荐指数
2
解决办法
1214
查看次数

标签 统计

.net ×1

c# ×1

multithreading ×1

random ×1

thread-safety ×1