Help me to understand why Select causes a retention
Hello,
I was profiling a WPF application while I encountered a small memory retention...
I have this base class which's a viewmodel
public class ManageFontModelBase<T> where T:class
{
public ObservableCollection<string> Fonts { get; set; }
public ObservableCollection<string> FontStyles { get; set; }
public ObservableCollection<string> FontSizes { get; set; }
public T Grid { get; set; }
public ManageFontModelBase()
{
Fonts = new ObservableCollection<string>();
FontStyles = new ObservableCollection<string>();
FontSizes=new ObservableCollection<string>();
var installedFontCollection = new InstalledFontCollection();
Fonts = new ObservableCollection<string>(installedFontCollection.Families.Select(x => x.Name));
FontStyles = new ObservableCollection<string>(typeof(FontStyles).GetProperties().Select(x => x.Name));
for (int i = 6; i < 79; i = i + 2)
{
FontSizes.Add($"{i}");
}
}
}
DotMemoring it (TM!) I got those two retention
The only way I've found to remove them is to do so
public ManageFontModelBase()
{
Fonts = new FastObservableCollection<string>();
FontStyles = new FastObservableCollection<string>();
FontSizes=new FastObservableCollection<string>();
using (var installedFontCollection = new InstalledFontCollection())
{
var fonts = installedFontCollection.Families
.ToList();
foreach (var font in fonts)
{
Fonts.Add(font.Name);
}
}
var propertyInfos = typeof(FontStyle).GetProperties();//.Select(p=>p.Name).ToList();
using (FontStyles.SuspendChangeNotifications())
{
foreach (var propertyInfo in propertyInfos)
{
FontStyles.Add(propertyInfo.Name);
}
}
using (FontSizes.SuspendChangeNotifications())
{
for (var i = MinFontSize; i < MaxFontSize; i = i + FontSizeStep)
{
FontSizes.Add($"{i}");
}
}
}
Why the Select cause those leak? Is it correct the way I've fixed it?
Thanks
Please sign in to leave a comment.
Hi Paolo,
Unfortunately I can't reproduce the case using the code you have provided. According what dotMemory displays there should be another one lambda (<>c<RadGridView>) with closure. Please check that provided code causes the issue - may be you have lost some part during simplifying it for the post.
I've analized better my code and the issue seems to be related to the fact I've a lamda (the .Select()) inside the constructor...so the compiler creates a pointer to the delegate for later use....