相关疑难解决方法(0)

C#锁定免费编码健全检查

更新:现在使用基于以下评论的只读集合

我相信下面的代码应该是线程安全的"锁定免费"代码,但是要确保我没有遗漏某些东西......

public class ViewModel : INotifyPropertyChanged
{
   //INotifyPropertyChanged and other boring stuff goes here...

   private volatile List<string> _data;
   public IEnumerable<string> Data
   {
      get { return _data; }
   }

   //this function is called on a timer and runs on a background thread
   private void RefreshData()
   {
      List<string> newData = ACallToAService();
      _data = newData.AsReadOnly();
      OnPropertyChanged("Data"); // yes, this dispatches the to UI thread
   }
}
Run Code Online (Sandbox Code Playgroud)

具体来说,我知道我可以使用一个lock(_lock)甚至是一个Interlocked.Exchange()但我不相信在这种情况下需要它.volatile关键字应该足够(以确保不缓存该值),不是吗?有人可以确认一下,或者让我知道我对线程的理解不清楚:)

c# multithreading volatile

1
推荐指数
2
解决办法
985
查看次数

标签 统计

c# ×1

multithreading ×1

volatile ×1