内存泄漏wcf与datacontract解析器

时间:2015-07-14 13:29:49

标签: .net wcf memory-leaks

我已经对我的wcf服务进行了简单测试 - 不断调用一个方法。然后我分析它的内存使用情况。

enter image description here

内存使用量不断增长。为什么?

enter image description here

主要内存占用者高于市场。

更新

我无法发布商业代码且代码太大。但我发现了一件有趣的事情。如果我的方法调用发出数据合同解析器的调用,则内存使用量会不断增长。如果方法调用没有发出datacontract解析器的调用,那么内存使用量不会增长。

我的datacontract解析器看起来像这样:

public class MyResolver : DataContractResolver
{
    public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, 
        out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
    {

        if (dataContractType == typeof(MyDerivedType))
        {
            XmlDictionary dictionary = new XmlDictionary();
            typeName = dictionary.Add("MyDerivedType");
            typeNamespace = dictionary.Add("http://tempuri.com");
            return true;
        }
        else
        {
            return knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace);
        }
    }
    ...
}

怎么了?

更新2

我做了简单的解决方法:

 public class MyResolver : DataContractResolver
{
    private static  Dictionary<string,XmlDictionary> _typesCache=new Dictionary<string, XmlDictionary>();
    static MyResolver()
    {
         XmlDictionary myDerivedTypeDictionary = new XmlDictionary();
         myDerivedTypeDictionary.Add("MyDerivedType");
         myDerivedTypeDictionary.Add("http://tempuri.com");
         _typesCache["MyDerivedType"] = myDerivedTypeDictionary ;
    }
     public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, 
        out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
    {
       if (dataContractType == typeof(MyDerivedType))
        {
            XmlDictionary dictionary = _typesCache["MyDerivedType"];
            XmlDictionaryString typeNameDictionaryString;
            dictionary.TryLookup("MyDerivedType", out typeNameDictionaryString);
            XmlDictionaryString namespaceDictionaryString;
            dictionary.TryLookup("http://tempuri.com", out namespaceDictionaryString);
            typeName = typeNameDictionaryString;
            typeNamespace = namespaceDictionaryString;

            return true;
        }
        ...
     }
     ...
}

并看到差异:

1.before

enter image description here

2.after

enter image description here

不是XmlDictionaryString不是int32 []的

1 个答案:

答案 0 :(得分:1)

为避免内存泄漏,请勿使用

XmlDictionary dictionary = new XmlDictionary();

在每次解决通话中