锁定属性get/set

本文关键字:set get 属性 锁定 | 更新日期: 2023-09-27 18:25:41

以下代码是否安全,多个线程正在访问一个属性,但没有写入特定对象。正在创建和指定新对象。多个线程调用CreateXmlDocReadXmlDoc

public class DataHolder
{
    public XmlDocument XmlDoc {get; set;}
}
public class AccessClass
{
    DataHolder dataHolderInstance;
    public AccessClass(DataHolder _dataHolder)
    {
        dataHolderInstance = _dataHolder;
    }
    private void CreateXmlDoc()
    {
        XmlDocument _xmlDoc = new XmlDocument();
        dataHolderInstance.XmlDoc = _xmlDoc;
    }
    private void ReadXmlDoc()
    {
        XmlNodeList elemList = dataHolderInstance.XmlDoc.GetElementsByTagName("title");
    }
}

锁定属性get/set

从纯粹的技术角度来看,您上面提供的代码不会出现任何线程安全问题(即数据损坏等)。。你必须问自己的问题是,从功能的角度来看,需要什么"线程安全"行为。

xml文档不是线程安全的。要使此代码线程安全:

public class DataHolder
{
    object lockObj = new object();
    private XmlDocument _xmlDoc;
    public XmlDocument XmlDoc
    { 
      get{return GetXmlDoc();}
      set{SetXmlDoc(value);}
    }
    private XmlDocument GetXmlDoc()
    {
       lock(lockObj) return _xmlDoc;
    }
    private void SetXmlDoc(XmlDocument xmlDoc)
    {
       lock(lockObj) _xmlDoc = xmlDoc;
    }
}
public class AccessClass
{
    DataHolder dataHolderInstance;
    public AccessClass(DataHolder _dataHolder)
    {
        dataHolderInstance = _dataHolder;
    }
    private void CreateXmlDoc()
    {
        XmlDocument _xmlDoc = new XmlDocument();
        dataHolderInstance.XmlDoc = _xmlDoc;
    }
    private void ReadXmlDoc()
    {
        XmlNodeList elemList = dataHolderInstance.XmlDoc.GetElementsByTagName("title");
    }
 }