我今天遇到了一些單碼在我們的代碼庫,我不知道,如果下面是線程安全的:的C原子性#合併運算
public static IContentStructure Sentence{
get {
return _sentence ?? (_sentence = new Sentence());
}
}
這種說法是等價於:
if (_sentence != null) {
return _sentence;
}
else {
return (_sentence = new Sentence());
}
我相信?只是一個編譯器技巧,並且生成的代碼仍然不是原子的。換句話說,在將_sentence設置爲新句子並返回之前,兩個或更多線程可能會發現_sentence爲空。
爲了保證原子性,我們不得不鎖定的代碼位:
public static IContentStructure Sentence{
get {
lock (_sentence) { return _sentence ?? (_sentence = new Sentence()); }
}
}
那是正確的?
http://csharpindepth.com/Articles/General/Singleton.aspx – SLaks 2012-02-23 19:58:52
除了你不能鎖定的東西是null,所以你的解決方案將永遠不會工作。 – vcsjones 2012-02-23 20:03:40
好點。是的,你必須創建另一個對象來鎖定。接得好。 – Adam 2012-02-23 20:09:59