C# Compiled lambda expressions instance creation and/or garbage collection?

自古美人都是妖i 提交于 2021-02-07 08:31:27

问题


Consider the following code sample:

using System;
using System.Linq.Expressions;

public class Class1<T, Y>
{
    public Class1(Expression<Func<T, Y>> mapExpression)
    {
        GetValue = mapExpression.Compile();
    }

    public Func<T, Y> GetValue { get; protected set; }
}

public class DataClass
{
    public long Data { get; set; }
}

Now suppose that I make in different places new instances of Class1, e.g.

var instance1 = new Class1<DataClass, long>(x => x.Data);
var instance2 = new Class1<DataClass, long>(x => x.Data);

When I do this, what happens:

  1. Do I get two different compiled functions?
  2. If so, do the two compiled functions get garbage collected when the instances of Class1 get garbage collected?
  3. If not, how can I avoid a memory leak (assuming that I can't realistically control the creation of Class1 instances)?

回答1:


  1. Yes. Make this static if 'singleton' is required.
  2. Before .NET 4, no, with .NET 4 dynamic created assemblies/code can be garbage collect under certain conditions.
  3. If the 'singleton' pattern does not work, try using a static caching mechanism.


来源:https://stackoverflow.com/questions/3940261/c-sharp-compiled-lambda-expressions-instance-creation-and-or-garbage-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!