Is locking access to a bool required or is it Overkill

前端 未结 3 1122
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 20:15

I have a class that is designed primarily as a POCO class, with various Threads and Tasks could read its values, and only others only occasionally updating these values. This se

3条回答
  •  死守一世寂寞
    2021-02-13 20:30

    Depending on how this is being used, you may need to mark the boolean volatile. This will require a backing field to your property.

    You should not need to handle this with the ReaderWriterLockSlim as you're doing now, since it's less than 32bits (assuming you're using AutoLayout, for details, see this post or, for the most detail, the section titled The Atomicity of Memory Accesses in the ECMA 335 spec). If you're using a type larger than this, then some form of synchronization will be required.

    I would recommend:

    public class MyClass
    {
        private volatile bool _theValue = false;
        public bool TheValue 
        {
            get { return _theValue; } 
            set { _theValue = value; } 
        }
     }
    

提交回复
热议问题