我最近採取了WCF Windows服務的所有權,使大量使用了下面的靜態實用工具類的檢索查找數據:這段代碼爲什麼會造成內存泄漏?
public static class Utility
{
//begin code that causes increased memory consumption
private static Dictionary<string, ErrorData> _errorData;
internal static Dictionary<string, ErrorData> ErrorData
{
get
{
if (_errorData == null)
{
_errorData = GetErrorData();
}
return _errorData;
}
}
//end code that causes increased memory consumption
/// GetErrorData method to get error messages from error xml
/// </summary>
/// <returns>Dictionary of Error messages value for different fields.</returns>
internal static Dictionary<string, ErrorData> GetErrorData()
{
Dictionary<string, ErrorData> data = null;
XmlDocument doc = LoadXmlDocument(Constants.ErrorMessagesFileName);
XmlNodeList errorNode = doc.SelectNodes("/ErrorMessages/Error");
data = new Dictionary<string, ErrorData>();
foreach (XmlNode node in errorNode)
{
ErrorData errorValues = new ErrorData();
errorValues.FieldName = node.Attributes["FieldName"].Value;
errorValues.ErrorMessage = node.Attributes["ErrorMessage"].Value;
data.Add(node.Attributes["code"].Value, errorValues);
}
return data;
}
internal static XmlDocument LoadXmlDocument(string xmlFileName)
{
XmlDocument doc = null;
try
{
if (HttpRuntime.Cache[xmlFileName] == null)
{
doc = new XmlDocument();
doc.Load(Constants.Folderpath + "\\" + xmlFileName);
HttpRuntime.Cache.Insert(xmlFileName, doc);
}
else
{
doc = (XmlDocument)HttpRuntime.Cache[xmlFileName];
}
}
catch (Exception ex)
{
//log
}
return doc;
}
}
正如你所看到的,靜態errordata子屬性使用了一個私人的後盾領域。 ErrorData是一個使用文件系統上的XML資源構建的字典,這就是爲什麼初次檢索時文件的內容存儲在HttpRuntime.Cache中的原因。
在正常負載下,該服務消耗大約120 MB的RAM。
在某些時候,一個團隊成員認爲需要通過創建一個由延遲加載的靜態字段支持的靜態屬性來引入另一個級別的優化。無論如何,在幾次調用服務之後,所述靜態字段的存在會導致嚴重的內存泄漏(500MB +)。
當我刪除靜態字段和屬性(客戶端改爲調用Utility.GetErrorData())時,內存消耗回到正常水平。
任何人都可以解釋爲什麼這個靜態字段的存在導致內存泄漏?如果這有所幫助,WCF服務將與InstanceContextMode.PerCall一起運行。
非常感謝。
你怎麼知道這是造成內存泄漏?它是不是隻是使用大量的內存,並保持它靜止?什麼是您的服務的實例?它是PerCall嗎?辛格爾頓?會議? – 2011-06-04 18:52:40
它實際上是內存泄漏還是GC運行不夠,或者認爲它不需要釋放內存。 – 2011-06-06 01:23:59
在DEBUG模式或RELEASE模式下運行?在RELEASE模式不會的情況下,DEBUG模式會泄漏。 – Felan 2011-06-08 20:26:34