WCF中的内存泄漏与DataContract Resolver

3

我对我的WCF服务进行了简单的测试——不断调用一个方法。然后我检查了它的内存使用情况。

enter image description here

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

enter image description here

上面显示的是主要的内存占用者。

更新

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

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

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.之前

enter image description here

2.之后

enter image description here

不是XmlDictionaryString,也不是int32[]。


2
你需要发布调用有问题函数的代码。 - 3-14159265358979323846264
1个回答

2
为了避免内存泄漏,请不要使用
XmlDictionary dictionary = new XmlDictionary();

在每次 resolve 调用中

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接