开发者

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

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 happen开发者_开发技巧s:

  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. 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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜