C#无锁编码完整性检查 [英] C# lock free coding sanity check

查看:96
本文介绍了C#无锁编码完整性检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

UPDATED: now using a read-only collection based on comments below

我认为以下代码应该是线程安全的无锁"代码,但要确保我没有丢失任何东西...

I believe that the following code should be thread safe "lock free" code, but want to make sure I'm not missing something...

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
   }
}

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

Specifically, I know that I could use a lock(_lock) or even an Interlocked.Exchange() but I don't believe that there is a need for it in this case. The volatile keyword should be sufficient (to make sure the value isn't cached), no? Can someone please confirm this, or else let me know what I don't understand about threading :)

推荐答案

这取决于意图.列表的获取/设置是原子的(即使没有volatile)和非缓存的(volatile),但是调用者可以更改列表,这不能保证线程安全.

It depends on what the intent is. The get/set of the list is atomic (even without volatile) and non-cached (volatile), but callers can mutate the list, which is not guaranteed thread-safe.

还有一种竞争条件可能会丢失数据:

There is also a race condition that could lose data:

 obj.Data.Add(value);

这里的值很容易被丢弃.

Here value could easily be discarded.

我将使用不可变(只读)集合.

I would use an immutable (read-only) collection.

这篇关于C#无锁编码完整性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆