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:
- Do I get two different compiled functions?
- If so, do the two compiled functions get garbage collected when the instances of Class1 get garbage collected?
- If not, how can I avoid a memory leak (assuming that I can't realistically control the creation of Class1 instances)?
- Yes. Make this static if 'singleton' is required.
- Before .NET 4, no, with .NET 4 dynamic created assemblies/code can be garbage collect under certain conditions.
- If the 'singleton' pattern does not work, try using a static caching mechanism.
精彩评论