.NET4 ExpandoObject使用会导致内存泄漏问题

7
我有一个继承的.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"

您可以在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”可能是在观察者眼中的,我想(我的眼睛也这么认为)。我是否遗漏了什么?.NET大师们是否认为这是正常和预期的?有没有一种方法可以让它清除掉东西?最好的方法是根本不要使用dynamic / ExpandoObject吗?

如果您使用Task.Factory.StartNew将foocall放在自己的线程上,内存泄漏是否仍然存在? - Craig Selbert
是的,但它只显示异常字符串的3个实例,无论我启动多少个线程。 - AngryPrimate
确认,在使用.NET框架4.7.2的Winform项目中存在内存泄漏问题。 - Jeson Martajaya
1个回答

12

这似乎是由于编译器生成的代码对动态属性访问进行了缓存。 (使用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__1是一个静态字段(位于私有嵌套类上),类型为CallSite<Func<CallSite,object,object>>。它保存对动态方法的引用,该方法在第一次访问foo.SomePropName时即时编译。(这可能是因为创建绑定很慢,所以缓存可大幅提高后续访问的速度。)
这个DynamicMethod包含对DynamicILGenerator的引用,后者引用了DynamicScope,最终持有一个令牌列表。其中一个令牌是动态生成的字符串'System.Dynamic.ExpandoObject' does not contain a definition for 'SomePropName'。该字符串存在于内存中,以便动态生成的代码可以抛出(和捕获)一个带有“正确”消息的RuntimeBinderException
总的来说,<>p__1字段使约2K数据保持活动状态(包括此字符串的172个字节)。没有受支持的方法可以释放这些数据,因为它被编译器生成的类型的静态字段锁住。 (当然,您可以使用反射将该静态字段设置为null,但这极度依赖于当前编译器的实现细节,并且很可能在未来损坏。)
从迄今为止我所见,似乎在C#代码中使用dynamic每个属性访问会分配约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;
}

哇塞。+10 详细信息! - AngryPrimate
@AngryPrimate 如果这个回答有帮助,请点赞或接受它! - Bradley Grainger
所以我猜如果我看到00或000个这些字符串挂在那里,我一定有一些对象没有正确处理?我想深入了解一下,大致上是这样的(简单地说):尝试访问,捕获异常,处理,返回值。我看到过帖子(在这里和其他地方),当使用IDictionary<string, object> foo = new ExpandoObject();时也报告了泄漏,但我还没有深入研究。我成功地将大多数ExpandoObject的用法更改为Dictionary,但有一些地方远非直截了当。 - AngryPrimate
我是一个 Stack Overflow 的新手,我的赞似乎还没有什么作用,但肯定被认为是“有帮助的”。 - AngryPrimate
在这个例子中,我无法重现创建数千个字符串的情况。每个C#表达式都有一个访问ExpandoObject的字符串(动态生成),因此如果您有大量属性访问,那么可能会创建数百个字符串。(在回答这个问题之前,我并没有真正使用过dynamic,因此可能存在其他使用dynamic的方式(我不熟悉)会分配更多的字符串。) - Bradley Grainger

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