.NET4 ExpandoObject使用泄漏内存

Ang*_*ate 6 .net memory-leaks expandoobject

我有一个继承的.NET 4.0应用程序作为Windows服务运行.我不是任何一个.NET专家,但在编写代码30多年后,我知道如何找到自己的方式.

当服务首次启动时,它会在大约70MB的私人工作集上进行计时.服务运行的时间越长,所需的内存就越多.这种增加并不是那么引人注目,只是坐着观看,但我们已经看到在应用程序运行了很长时间(100天以上)之后的情况,它达到了多GB(当前记录为5GB).我将ANTS Memory Profiler附加到正在运行的实例上,发现ExpandoObject的使用似乎占用了几兆字节的字符串,这些字符串不会被GC清理掉.可能还有其他泄漏,但这是最明显的,所以它首先受到攻击.

我从其他SO帖子中了解到,当读取(但不是写入)动态分配的属性时,ExpandoObject的"正常"使用会生成内部RuntimeBinderException.

dynamic foo = new ExpandoObject();
var s;
foo.NewProp = "bar"; // no exception
s = foo.NewProp;     // RuntimeBinderException, but handled by .NET, s now == "bar"
Run Code Online (Sandbox Code Playgroud)

你可以在VisualStudio中看到异常,但最终它是在.NET内部处理的,你得到的就是你想要的值.

除了...异常的Message属性中的字符串似乎保留在堆上,并且永远不会收到Garbage Collected,即使在生成它的ExpandoObject超出范围之后很久.

简单的例子:

using System;
using System.Dynamic;

namespace ConsoleApplication2
{
   class Program
   {
      public static string foocall()
      {
         string str = "", str2 = "", str3 = "";
         object bar = new ExpandoObject();
         dynamic foo = bar;
         foo.SomePropName = "a test value";
         // each of the following references to SomePropName causes a RuntimeBinderException - caught and handled by .NET
         // Attach an ANTS Memory profiler here and look at string instances
         Console.Write("step 1?");
         var s2 = Console.ReadLine();
         str = foo.SomePropName;
         // Take another snapshot here and you'll see an instance of the string:
         // 'System.Dynamic.ExpandoObject' does not contain a definition for 'SomePropName'
         Console.Write("step 2?");
         s2 = Console.ReadLine();
         str2 = foo.SomePropName;
         // Take another snapshot here and you'll see 2nd instance of the identical string
         Console.Write("step 3?");
         s2 = Console.ReadLine();
         str3 = foo.SomePropName;

         return str;
      }
      static void Main(string[] args)
      {
         var s = foocall();
         Console.Write("Post call, pre-GC prompt?");
         var s2 = Console.ReadLine();
         // At this point, ANTS Memory Profiler shows 3 identical strings in memory
         // generated by the RuntimeBinderExceptions in foocall. Even though the variable
         // that caused them is no longer in scope the strings are still present.

         // Force a GC, just for S&G
         GC.Collect();
         GC.WaitForPendingFinalizers();
         GC.Collect();
         Console.Write("Post GC prompt?");
         s2 = Console.ReadLine();
         // Look again in ANTS.  Strings still there.
         Console.WriteLine("foocall=" + s);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我认为"虫子"在观看者的眼中(我的眼睛说虫子).我错过了什么吗?这是正常的,并由组中的.NET主人预期?有没有办法告诉它清除事情?是不是首先不使用dynamic/ExpandoObject的最佳方法?

Bra*_*ger 10

这似乎是由于编译器生成的代码为动态属性访问执行的缓存.(使用VS2015和.NET 4.6的输出执行分析;其他编译器版本可能会产生不同的输出.)

str = foo.SomePropName;编译器将调用重写为类似的东西(根据dotPeek;注意<>o__0等等是非合法C#但由C#编译器创建的标记):

if (Program.<>o__0.<>p__2 == null)
{
    Program.<>o__0.<>p__2 = CallSite<Func<CallSite, object, string>>.Create(Binder.Convert(CSharpBinderFlags.None, typeof (string), typeof (Program)));
}
Func<CallSite, object, string> target1 = Program.<>o__0.<>p__2.Target;
CallSite<Func<CallSite, object, string>> p2 = Program.<>o__0.<>p__2;
if (Program.<>o__0.<>p__1 == null)
{
    Program.<>o__0.<>p__1 = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "SomePropName", typeof (Program), (IEnumerable<CSharpArgumentInfo>) new CSharpArgumentInfo[1]
    {
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string) null)
    }));
}
object obj3 = Program.<>o__0.<>p__1.Target((CallSite) Program.<>o__0.<>p__1, obj1);
string str1 = target1((CallSite) p2, obj3);
Run Code Online (Sandbox Code Playgroud)

Program.<>o__0.<>p__1是类型的静态字段(在私有嵌套类上)CallSite<Func<CallSite,object,object>>.它包含对第一次foo.SomePropName访问时按需编译的动态方法的引用.(可能这是因为创建绑定很慢,因此缓存它会在后续访问中显着提高速度.)

DynamicMethod包含对引用最终包含令牌列表的DynamicILGenerator引用DynamicScope.其中一个令牌是动态生成的字符串'System.Dynamic.ExpandoObject' does not contain a definition for 'SomePropName'.该字符串存在于内存中,因此动态生成的代码可以RuntimeBinderException使用"正确"消息抛出(并捕获)a .

总的来说,该<>p__1字段保持大约2K的数据存活(包括该字符串的172个字节).没有支持的方法来释放这些数据,因为它的根源是编译器生成的类型上的静态字段.(当然,您可以使用反射将静态字段设置为null,但这将非常依赖于当前编译器的实现细节,并且很可能在将来中断.)

从我到目前为止所看到的,似乎dynamic在C#代码中使用每个属性访问分配大约2K的内存; 你可能只需要考虑使用动态代码的价格.但是(至少在这个简化的例子中),该内存仅在代码第一次执行时分配,因此程序运行的时间越长,就不应该继续使用更多内存; 可能存在不同的泄漏,将工作设置推至5GB.(字符串有三个实例,因为有三行独立的代码执行foo.SomePropName;但是,如果调用foocall100次,仍然只有三个实例.)

为了提高性能并减少内存使用,您可能需要考虑使用Dictionary<string, string>Dictionary<string, object>作为更简单的键/值存储(如果可以通过编写代码的方式).请注意,ExpandoObject实现IDictionary<string, object>以下小重写产生相同的输出,但避免了动态代码的开销:

public static string foocall()
{
    string str = "", str2 = "", str3 = "";

    // use IDictionary instead of dynamic to access properties by name
    IDictionary<string, object> foo = new ExpandoObject();

    foo["SomePropName"] = "a test value";
    Console.Write("step 1?");
    var s2 = Console.ReadLine();

    // have to explicitly cast the result here instead of having the compiler do it for you (with dynamic)
    str = (string) foo["SomePropName"];

    Console.Write("step 2?");
    s2 = Console.ReadLine();
    str2 = (string) foo["SomePropName"];
    Console.Write("step 3?");
    s2 = Console.ReadLine();
    str3 = (string) foo["SomePropName"];

    return str;
}
Run Code Online (Sandbox Code Playgroud)