List<SomeObject>.Count 是否需要 ReaderWriterLockSlim.EnterReadLock? [英] Is ReaderWriterLockSlim.EnterReadLock necessary for List&lt;SomeObject&gt;.Count?

查看:36
本文介绍了List<SomeObject>.Count 是否需要 ReaderWriterLockSlim.EnterReadLock?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

someList.Count 在 C# 中是线程安全的吗?

Is someList.Count thread safe in C#?

性能对我来说很重要,由于主程序的复杂性,我不能使用其他线程安全的集合

Performance is very important to me and I can not use other thread safe collections due to the complexity of the main program

我知道还有很多其他情况,但只关注这个简单的问题:

I know there can be many other cases, but just focus on this simple question:

_lock.EnterReadLock 对于 someList.Count 是否必要,因为它可能是一个原子属性?

Is _lock.EnterReadLock necessary for someList.Count or not because it might be an atomic attribute?

private ReaderWriterLockSlim _lock;
private List<SomeObject> _someList;

public void Add(SomeObject obj)
{
    try
    {
        _lock.EnterReadLock();
                
        if (_someList.Count < 10)
        {
            try
            {
                _lock.EnterWriteLock();

                _someList.Add(obj);
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
    }
    finally
    {
        _lock.ExitReadLock();
    }
}

推荐答案

不写 _lock.EnterReadLock() 也不会例外,但是 list.Count 可能不是预期的数字,所以最好使用_lock.EnterReadLock() 如果我们现在需要确切的 list.Count !

There will be no exception by not writing the _lock.EnterReadLock(), but the list.Count may not be expected number, so it is better to use the _lock.EnterReadLock() if we need the exact list.Count at the moment!

这篇关于List<SomeObject>.Count 是否需要 ReaderWriterLockSlim.EnterReadLock?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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