1
鎖定力量變量是否直接寫入內存而不是像volatile那樣緩存嗎?在this question Orion Edwards指出使用鎖比使用volatile更好,但是如果從鎖內訪問公共變量並始終從該鎖訪問,這是否意味着它永遠不會被緩存在此鎖語句之外?使用鎖定和易失性緩存變量
private readonly object locker = new object();
private bool? _Var = null;
public bool? Var
{
get
{
lock (locker)
{
//possibly get the variable _Var in cache memory somewhere
return this._Var;
//force _Var back to memory
}
}
set
{
lock (locker)
{
//possibly get the variable _Var in cache memory somewhere
this._Var = value;
//force _Var back to memory
}
}
}
好吧,如果我是正確的鎖確實保護_Var變量,如我在代碼中所述?在這個例子中使用鎖是安全的? – Jeffnl
@Jeff是的,它是安全的,因爲在讀取時不會被緩存。 – dcastro