更新对不可变对象的引用的首选方法是什么? [英] What is the preferred method of updating a reference to an immutable object?

查看:27
本文介绍了更新对不可变对象的引用的首选方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个像 ImmutableList() 这样的不可变对象.在多线程环境中使用此对象的首选方法是什么?

In case we have an immutable object like an ImmutableList(). What is the preferred method for using this object in a multi threaded environment?

例如

public class MutableListOfObjects()
{
   private volatile ImmutableList objList;

   public class MutableListOfObjects()
   {
       objList = new ImmutableList();
   }

   void Add(object o)
   {
      // Adding a new object to a list will create a new list to ensure immutability of lists.

      // Is declaring the object as volatile enough or do we want to
      // use other threading concepts?
      objList = objList.Add(o);
   }

   // Will objList always use that lest version of the list
   bool Exist(object o)
   {
      return objList.Exist(o);
   }
}

声明引用 volatile 是否足以实现所需的行为?还是最好使用其他线程函数?

Is declaring the reference volatile sufficient for achieving the desired behavior? Or is it preferable to use other threading functions?

推荐答案

首选"是上下文.最简单的方法是使用lock,在大多数情况下,这将非常有效地完成这项工作.如果您有充分的理由认为 lock 有问题,那么 Interlocked 很有用:

"Preferred" is contextual. The simplest approach is to use a lock, and in most cases that will do the job very effectively. If you have good reason to think that lock is a problem, then Interlocked is useful:

bool retry;
do {
    var snapshot = objList;
    var combined = snapshot.Add(o);
    retry = Interlocked.CompareExchange(ref objList, combined, snapshot)
              != snapshot;
} while(retry);

这基本上适用于乐观的但检查路径:大多数时候,它只会通过一次.偶尔有人会在我们不查找时更改 objList 的值 - 没关系,我们再试一次.

This basically works on an optimistic but checked path: most times through, it'll only go through once. Occasionally somebody will change the value of objList while we aren't looking - that's fine, we just try again.

然而,有一些线程安全列表等的预装实现,由真正知道他们在说什么的人提供.考虑使用 ConcurrentBag 等.或者只是一个带有 lockList.

There are, however, pre-canned implementations of thread-safe lists etc, by people who really know what they are talking about. Consider using ConcurrentBag<T> etc. Or just a List<T> with a lock.

这篇关于更新对不可变对象的引用的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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