下面的胎面是否以單件模式安全運行?我使用第四個單例模式在http://csharpindepth.com/Articles/General/Singleton.aspxSingleton中的輸出參數
我擔心使用輸出參數將打破整個主體。
public sealed class eCacheContent
{
private static readonly eCacheContent instance = new eCacheContent();
private ICacheManager _Cache = CacheFactory.GetCacheManager(ConfigurationManager.AppSettings["ContentCache"].ToString());
// for access method control locking
private static object syncRoot = new object();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static eCacheContent() { }
private eCacheContent() { }
public static eCacheContent Instance
{
get
{
return instance;
}
}
public bool TryGetValue(string key, out eContent output)
{
lock (syncRoot)
{
if (Contains(key))
{
ObjectCloner helper = new ObjectCloner();
eContent tmp = (eContent)this._Cache.GetData(key);
output = helper.Clone(tmp);
return true;
}
output = new eContent();
return false;
}
}
public void Add(string key, object value)
{
// Initiase the helper class for cloning
if (CheckKeyIfValid(key))
{
ObjectCloner helper = new ObjectCloner();
// Remove if already exist
this.Remove(key);
// Add carbon copy
_Cache.Add(key, helper.Clone(value));
}
}
public void Flush()
{
_Cache.Flush();
}
private bool Contains(string key)
{
if (CheckKeyIfValid(key))
return _Cache.Contains(key);
else
return false;
}
private void Remove(string key)
{
if (Contains(key))
{
_Cache.Remove(key);
}
}
private bool CheckKeyIfValid(string key)
{
if ((key != null) && (key.Trim().Length != 0))
return true;
return false;
}
}
你的方法是* instance *方法,而不是'static' - 我認爲這是一個錯誤? – James
我會說這確實是一個壞主意。當你鎖定這段代碼時,其他線程可能正在訪問你的「out」變量。不要試圖鎖定這個var,因爲這可能會導致死鎖。所以我會說:壞主意。無論如何,爲什麼使用ref呢?只需返回字符串。這不是C++,成員是引用計數。 – Samuel
我看到我的思路出錯了。它總是有幫助的獲得一個外觀...謝謝 – user3111634