2014-10-05 99 views
0

下面的代碼是否安全,多線程正在訪問屬性但不寫入特定對象。新對象正在創建和分配。多線程調用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"); 
    } 

} 
+0

在訪問類中初始化數據持有者實例在哪裏?它是否在訪問類之間共享? – Rup 2014-10-05 21:52:22

+1

請更改。多個線程調用'CreateXmlDoc'嗎?如果是這樣,那麼不,它不是線程安全的。 – 2014-10-05 21:52:29

+0

@SimonWhitehead是多線程調用'CreateXmlDoc' – swiftcode 2014-10-05 22:02:48

回答

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

從純技術的角度來看,因爲你在上面提供的代碼,也不會表現出任何線程安全問題(即數據損壞等)..你要問自己的問題從功能角度來看,需要什麼「線程安全」行爲。