Nathan
Nathan

Reputation: 10784

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 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)?

Upvotes: 4

Views: 1094

Answers (1)

leppie
leppie

Reputation: 117260

  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.

Upvotes: 3

Related Questions