序列化器中是否存在内存泄漏

时间:2018-10-30 11:54:06

标签: c# .net

在下面的代码中,代码中是否有任何部分可能导致内存泄漏? XmlSerializer会导致内存泄漏吗?

public static string Serializer<T>(T tag, Encoding encoding = null)
    {
        if (encoding == null)
            encoding = Encoding.UTF8;

        MemoryStream memoryStream = null;
        try
        {
            StringBuilder xmlBuilder = new StringBuilder();
            memoryStream = new MemoryStream();
            using (StreamWriter streamWriter = new StreamWriter(memoryStream, encoding))
            {
                XmlSerializer serializer = new XmlSerializer(tag.GetType());
                serializer.Serialize(streamWriter, tag);

                using (StreamReader streamREader = new StreamReader(memoryStream, encoding))
                {
                    memoryStream.Position = 0;
                    xmlBuilder.Append(streamREader.ReadToEnd());
                }
            }
            return xmlBuilder.ToString();
        }
        catch (Exception ex)
        {
            logger.Error("{0} {1}", "Serializer failed ", ex);
            return null;
        }
    }

任何想法。

1 个答案:

答案 0 :(得分:-2)

您不会处理在6上声明的“ memoryStream”。

还有其他事情:在GC通过之前,您将看不到内存缺口的恢复...您可以使用GC.Collect

进行检查