List<SomeObject>.Count 是否需要 ReaderWriterLockSlim.EnterReadLock?

编程入门 行业动态 更新时间:2024-10-26 10:29:26
本文介绍了List<SomeObject>.Count 是否需要 ReaderWriterLockSlim.EnterReadLock?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 16:22:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396242.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SomeObject   lt   List   gt   EnterReadLock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!