我对我的WCF服务进行了简单的测试——不断调用一个方法。然后我检查了它的内存使用情况。
内存使用量不断增长。但是为什么呢?
上面显示的是主要的内存占用者。
更新
我无法发布商业代码,而且代码太大了。但我发现了一件有趣的事情。如果我的方法调用会触发数据合同解析器的调用,则内存使用量会不断增长。如果方法调用不会触发数据合同解析器的调用,则内存使用量不会增长。
我的数据合同解析器如下:
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.之前
2.之后
不是XmlDictionaryString,也不是int32[]。