.NET4 ExpandoObject 使用泄漏内存

标签 .net memory-leaks expandoobject

我有一个继承的 .NET 4.0 应用程序,它作为 Windows 服务运行。无论如何,我都不是 .NET 专家,但是在编写了 30 多年的代码之后,我知道如何找到自己的出路。

当服务第一次启动时,它的私有(private)工作集大约为 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"

您可以在 VisualStudio 中看到异常发生,但最终它是在 .NET 内部处理的,您得到的只是您想要的值。

除了... 异常的 Message 属性中的字符串似乎停留在堆上并且永远不会被垃圾收集,即使在生成它的 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);
      }
   }
}

“ bug ”在旁观者的眼中,我想(我的眼睛说 bug )。我错过了什么吗?这是正常的并且是小组中的 .NET 大师所期望的吗?有什么办法可以告诉它清除这些东西吗?首先不使用动态/ExpandoObject 的最佳方法是什么?

最佳答案

这似乎是由于编译器为动态属性访问生成的代码执行的缓存。 (使用 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);
Program.<>o__0.<>p__1CallSite<Func<CallSite,object,object>> 类型的静态字段(在私有(private)嵌套类上) .它包含对第一次按需编译的动态方法的引用foo.SomePropName被访问。 (大概这是因为创建绑定(bind)很慢,所以缓存它可以显着提高后续访问的速度。)

这个DynamicMethod持有对 DynamicILGenerator 的引用其中引用了 DynamicScope最终包含一个 token 列表。这些标记之一是动态生成的字符串 'System.Dynamic.ExpandoObject' does not contain a definition for 'SomePropName' .该字符串存在于内存中,因此动态生成的代码可以抛出(并捕获)RuntimeBinderException。带有“正确”的信息。

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

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

为了提高性能和减少内存使用,您可能需要考虑使用 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;
}

关于.NET4 ExpandoObject 使用泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42519547/

相关文章:

c# - 如何在 C# 中递归遍历并记录 HttpRequestMessage 的属性?

c# - 为什么我不能在隐式转换时返回接口(interface),而 ExpandoObject 可以?

.net - QT4 与 .Net 相比如何

.net - CollectionViewSources 可以嵌套吗?

c - 使用 strcat() 作为函数的参数

python - Tensorflow 在打开和关闭每个 session 时泄漏 1280 字节?

c# - 为什么 LINQ 无法将 DataRows 添加到 DataTable?

c# - 开发人员开始从SQL迁移到NO-SQL(CouchDB,FathomDB,MongoDB等)时必须采取哪些 “mental steps”?

.net - 将 Excel 2007 数据保存到新的 PowerPoint 演示文稿

javascript - Angularjs Dom 在加载模板时泄漏