Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy is this code causing a memory leak?
    text
    copied!<p>I've recently taken ownership of a WCF Windows Service that makes heavy use of the following static Utility class to retrieve lookup data:</p> <pre><code> public static class Utility { //begin code that causes increased memory consumption private static Dictionary&lt;string, ErrorData&gt; _errorData; internal static Dictionary&lt;string, ErrorData&gt; 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 /// &lt;/summary&gt; /// &lt;returns&gt;Dictionary of Error messages value for different fields.&lt;/returns&gt; internal static Dictionary&lt;string, ErrorData&gt; GetErrorData() { Dictionary&lt;string, ErrorData&gt; data = null; XmlDocument doc = LoadXmlDocument(Constants.ErrorMessagesFileName); XmlNodeList errorNode = doc.SelectNodes("/ErrorMessages/Error"); data = new Dictionary&lt;string, ErrorData&gt;(); 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; } } </code></pre> <p>As you can see, the static ErrorData property makes use of a private backing field. ErrorData is a Dictionary that is constructed using an XML resource on the filesystem, which is why the contents of the file are stored in HttpRuntime.Cache upon initial retrieval. </p> <p>Under normal load, the service consumes about 120 MB of RAM.</p> <p>At some point, a team member felt the need to introduce another level of optimization by creating a static property backed by a lazily loaded static field. Anyway, the presence of said static field causes a rather severe memory leak (500MB+ ) after just a few calls to the service. </p> <p>The minute I remove the static field and property (clients instead call Utility.GetErrorData()), memory consumption goes back to normal levels.</p> <p>Can anyone explain why the presence of this static field is causing a memory leak? The WCF service is running with InstanceContextMode.PerCall, if that makes a difference.</p> <p>Many thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload