不受保护地访问属性中的成员 get [英] unprotected access to member in property get

查看:47
本文介绍了不受保护地访问属性中的成员 get的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有房产

    public ObservableCollection<string> Name
    {
        get
        {
            return _nameCache;
        }
    }

_nameCache 由其他类方法中的多个线程更新.更新由锁保护.问题是:我应该在 return 语句周围使用相同的锁吗?不使用锁会导致竞争条件吗?

_nameCache is updated by multiple threads in other class methods. The updates are guarded by a lock. The question is: should I use the same lock around my return statement? Will not using a lock lead to a race condition?

推荐答案

这取决于您所说的更新是什么意思.

It depends on what you mean by updated.

如果你的意思是引用被修改,即_nameCache = newvalue;,那么正如马克所说,是的,你应该(使用相同的锁),不,你不会得到竞争条件.

If you mean that the reference is modified, i.e. _nameCache = newvalue;, then as Mark has said, yes you should (with the same lock) and, no, you won't get a race condition.

但是,如果您的意思是向 _nameCache 引用的实例添加和删除项目,那么您不需要锁定返回(因为引用本身永远不会改变).但是,在检索集合之后,您必须小心读取集合的方式 - 理想情况下,您应该在调用其任何方法之前使用相同的锁.

If, however, you mean that items are added and removed to the instance referenced by _nameCache, then you won't need to lock on return (since the reference itself never changes). However, you will have to be careful how you read the collection after retrieving it - ideally you should then use the same lock before calling any of its methods.

或者,如果您需要做的只是跟踪更改,则可以使用事件模型来通知新项目等 - 因为事件将在当前具有集合锁定的线程上引发.

Either that, or you can use the event model to be notified of new items etc if all you need to do is to track changes - since the events will be raised on the thread that currently has the lock to the collection.

如果这不合适(因为您总是通过索引器或其他方式获取元素),那么您始终可以通过此属性返回 ObservableCollection 的副本 - 即 return new ObservableCollection(_nameCache);.这将使属性的返回值短暂存在,但让任何调用者可以自由地枚举和索引,而不必担心其他线程的状态损坏.

If this is not suitable (because you're always getting elements via an indexer or whatever), then you could always return a copy of the ObservableCollection through this property - i.e. return new ObservableCollection<string>(_nameCache);. This will make the return value of the property short-lived, but leaves any caller free to enumerate and index without any fears of state corruption from other threads.

这篇关于不受保护地访问属性中的成员 get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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