C# 线程和阻塞

标签 c# multithreading

<分区>

我想知道哪种方法以线程安全方式加载数据更好。传统上,我使用双锁模式,并且效果很好。现在,随着 System.Lazy 类型的添加,我想知道依赖 Lazy 和 Loading 的内部结构是否更好,并以更好的方式完成工作。它确实看起来更干净、更易于阅读,但它更好吗?

有什么想法吗?

namespace SomeNameSpace
{
  public class DataStoreContext
  {
    private readonly static Lazy<DataStoreContext> context = new Lazy<DataStoreContext>(() => new DataStoreContext());
    private Lazy<Dictionary<string, Entity>> _entities = new Lazy<Dictionary<string, Entity>>(() => { return DataStoreContext.Instance.Load(); });
    private readonly object _syncRoot = new object();
    private DataStoreContext()
    {
    }

    public Dictionary<string, Entity> Data
    {
      get { return _entities.Value; }
    }

    public static DataStoreContext Instance
    {
      get { return context.Value; }
    }

    private Dictionary<string, Entity> Load()
    {
      // Load Data from some data store. 
      return null;
    }

    private Dictionary<string, Entity> LoadWithLock()
    {
      if (_entities == null)
      {
        lock (_syncRoot)
        {
          if (_entities == null)
          {
            Dictionary<string, Entity> entities = this.Load();
            _entities = entities;
            return _entities;
          }
        }
      }

      return _entities ;
    }

    public void Clear()
    {

     _entities = new Lazy<Dictionary<string, Entity>>(() => { return DataStoreContext.Instance.Load(); });

    }
  }
}

最佳答案

It does look cleaner and easier to read but is it better?

是的。双重检查锁定很难做到正确。它需要一个内存屏障才能正确。 CIL* 实际上并不能保证您的实现安全。

有关详细信息,请参阅 this Wikipedia entry .

通过使用 Lazy<T> ,您得到的代码不仅更清晰,而且实际上在所有平台上都是正确的。

*请注意,由于平台的内存模型,这可能在运行 Microsoft 运行时的 x86 和 x64 上完美运行。但是,如果没有适当的内存屏障,规范不能保证它是正确的。

关于C# 线程和阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12810549/

相关文章:

c# - 对象数组,在一个线程中更新并在另一个线程中读取

c# - 如何处理静态类中错误的appSettings?

c++ - 线程上下文的静态存储对象优化

c# - 检测到没有响应的线程并终止它?

c# - 使用 DES key 计算 KCV

c# - 如何将数字格式化为带前导零的字符串?

c# - Unity 2D C# 在 Canvas 上实例化 Sprite 。找不到问题所在

java - 线程是否开始使用与其他对象相同的方式收集 'new Thread(r).start()' 垃圾?

c# - C#中issue/response串口处理

c++ - 错误 C2248 : 'std::promise<_Ty>::promise' : cannot access private member declared in class 'std::promise<_Ty>'