内存泄漏 wcf 与 datacontract 解析器

Memory leak wcf with datacontract resolver

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

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

主要内存占用在市场上面。

更新

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

我的数据合同解析器如下所示:

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

2.after

不是 XmlDictionaryString 不是 int32[] 的

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

XmlDictionary dictionary = new XmlDictionary();

在每次解析调用中