admin管理员组

文章数量:1295948

I'm currently investigating a potential memory leak in a windows service, and encountered the below static class with static methods which we are calling to transform/generate XML. Could this cause a memory leak even though we have "using" statements? And would it be better practice to use a non-static class for this functionality instead?

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;

public static class XSLTTransformHelpers
    {
        /// <summary>
        /// Transforms an xml formatted string using an xslt transform
        /// </summary>
        /// <param name="inputDataXML">The input data to be transformed</param>
        /// <param name="inputTransformXML">The transfer to be used</param>
        /// <returns>The transformed xml formatted string</returns>
        public static string Transform(string inputDataXML, string inputTransformXML)
        {
            using (var xsltInputReader = new StringReader(inputTransformXML))
            using (var xsltXmlReader = XmlReader.Create(xsltInputReader))
            {
                var xslt = new XslCompiledTransform();
                xslt.Load(xsltXmlReader);

                using (var results = new StringWriter())
                using (var inputReader = XmlReader.Create(new StringReader(inputDataXML)))
                {
                    xslt.Transform(inputReader, null, results);
                    return results.ToString();
                }
            }
        }

        /// <summary>
        /// Serializes an object into an xml string
        /// </summary>
        /// <typeparam name="T">The object type to be serialized into xml</typeparam>
        /// <param name="objectToSerialize">The object to be serialized</param>
        /// <returns>The object serialized as an xml string</returns>
        public static string GetXml<T>(T objectToSerialize)
        {

            XmlAttributes attrs = new XmlAttributes();
            XmlAttributeOverrides xOver = new XmlAttributeOverrides();
            XmlRootAttribute xRoot = new XmlRootAttribute();

            // Set a new Namespace and ElementName for the root element.
            xRoot.ElementName = objectToSerialize.GetType().Name;
            attrs.XmlRoot = xRoot;

            /* Add the XmlAttributes object to the XmlAttributeOverrides. 
               No  member name is needed because the whole class is 
               overridden. */
            xOver.Add(typeof(T), attrs);

            var xmlSubmit = new XmlSerializer(typeof(T), xOver);

            using (var stringWriter = new StringWriter())
            using (var xmlWriter = XmlWriter.Create(stringWriter))
            {
                try
                {
                    xmlSubmit.Serialize(stringWriter, objectToSerialize);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return stringWriter.ToString();
            }
        }
    }

I'm currently investigating a potential memory leak in a windows service, and encountered the below static class with static methods which we are calling to transform/generate XML. Could this cause a memory leak even though we have "using" statements? And would it be better practice to use a non-static class for this functionality instead?

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;

public static class XSLTTransformHelpers
    {
        /// <summary>
        /// Transforms an xml formatted string using an xslt transform
        /// </summary>
        /// <param name="inputDataXML">The input data to be transformed</param>
        /// <param name="inputTransformXML">The transfer to be used</param>
        /// <returns>The transformed xml formatted string</returns>
        public static string Transform(string inputDataXML, string inputTransformXML)
        {
            using (var xsltInputReader = new StringReader(inputTransformXML))
            using (var xsltXmlReader = XmlReader.Create(xsltInputReader))
            {
                var xslt = new XslCompiledTransform();
                xslt.Load(xsltXmlReader);

                using (var results = new StringWriter())
                using (var inputReader = XmlReader.Create(new StringReader(inputDataXML)))
                {
                    xslt.Transform(inputReader, null, results);
                    return results.ToString();
                }
            }
        }

        /// <summary>
        /// Serializes an object into an xml string
        /// </summary>
        /// <typeparam name="T">The object type to be serialized into xml</typeparam>
        /// <param name="objectToSerialize">The object to be serialized</param>
        /// <returns>The object serialized as an xml string</returns>
        public static string GetXml<T>(T objectToSerialize)
        {

            XmlAttributes attrs = new XmlAttributes();
            XmlAttributeOverrides xOver = new XmlAttributeOverrides();
            XmlRootAttribute xRoot = new XmlRootAttribute();

            // Set a new Namespace and ElementName for the root element.
            xRoot.ElementName = objectToSerialize.GetType().Name;
            attrs.XmlRoot = xRoot;

            /* Add the XmlAttributes object to the XmlAttributeOverrides. 
               No  member name is needed because the whole class is 
               overridden. */
            xOver.Add(typeof(T), attrs);

            var xmlSubmit = new XmlSerializer(typeof(T), xOver);

            using (var stringWriter = new StringWriter())
            using (var xmlWriter = XmlWriter.Create(stringWriter))
            {
                try
                {
                    xmlSubmit.Serialize(stringWriter, objectToSerialize);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return stringWriter.ToString();
            }
        }
    }
Share Improve this question asked Feb 12 at 10:16 PonsiettaPonsietta 3197 silver badges17 bronze badges 7
  • 5 I don't see how static is relevant here. But no, this shouldn't be causing any leaks as far as I can see. There's nothing problematic about having static methods that dispose of things. (I would remove the try/catch block though - that's a purely negative bit of code at the moment, as it loses the detail in the stack trace, as well as adding 7 pointless lines of code.) – Jon Skeet Commented Feb 12 at 10:24
  • XslCompiledTransform might be leaking, I know XmlSerializer has a known memory leak in certain situations. Look through your memory profile (which you should start with to investigate leaks) for many instances of DynamicMethod or DynamicAssembly or other indications of dynamically loaded code. See also tessferrandez/blog/2010/05/05/… – Charlieface Commented Feb 12 at 11:21
  • Look at Dynamically generated assemblies. – Alexander Petrov Commented Feb 12 at 12:42
  • Oops: using (var inputReader = XmlReader.Create(new StringReader(inputDataXML))) .... the "imbedded" StringReader. – Gerry Schmitz Commented Feb 12 at 19:18
  • 1 @GerrySchmitz What's wrong with that? XmlReader will dispose it by default, and in any case StringReader does not hold unmanaged memory. – Charlieface Commented Feb 13 at 13:36
 |  Show 2 more comments

1 Answer 1

Reset to default 1

That is perfectly fine. There is no problem with static methods from a memory leak perspective. It is static mutable state, i.e. fields or properties, you want to be careful with. There is no reason to rewrite the class to be non static. As far as I can see the posted code looks completely fine.

The best way to investigate memory leaks is with a memory profiler. That should allow you to see what types of objects are leaking, and what is retaining them.

本文标签: cCreating disposable objects in static methodsStack Overflow