锁定属性获取/设置

时间:2014-10-05 21:48:27

标签: c# .net

以下代码是否安全,多个线程正在访问属性但未写入特定对象。正在创建和分配新对象。多个线程调用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");
    }

}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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");
    }
 }