Reputation: 24063
My class has complicated property:
private Image m_LogoImage=null;
public Image LogoImage
{
get
{
if (m_LogoImage == null && File.Exists(Data.LogoFileUrl))
{
DrawingImage image = DrawingImage.FromFile(Data.LogoFileUrl);
m_LogoImage = Image.GetInstance(image, new Color(1, 1, 1));
}
return m_LogoImage;
}
}
LogoImage.get is very slow and resource consuming action to the first time the client calls it, the property calculate the image and stored the result in private variable m_LogoImage.
This looks to me very basic. .NET support automatic properties (public string P {get;set;}
). Does it support automatic storing of complicated properties?
Upvotes: 0
Views: 580
Reputation: 4893
From the looks of it: DrawingImage.FromFile(Data.LogoFileUrl);
your data is coming from some sort of static object. Your current approach of per class instance based loading is loading the same the object over and over again at every new instance. You can optimize by preloading your data into a static object at initial run time. E.g.:
private static Image _m_LogoImage = DrawingImage.FromFile(Data.LogoFileUrl);
public Image LogoImage
{
get { return _m_LogoImage; }
}
Upvotes: 0
Reputation: 12667
There're a number of state based concerns, so there's no language level mechanics for lazy load.
You can however use the Lazy<T>
class to accomplish this functionality.
private Lazy<Image> logo = new Lazy(() => LoadImage());
public Image LogoImage
{
get
{
return logo.Value;
}
}
You can also use the null coalescing operator (??
) to do lazy load for nullable types.
get
{
return image ?? (image = LoadImage());
}
Upvotes: 5
Reputation: 85645
No - it does not support "automatic storing of complicated properties" - since then it'd mean it'd have to support "automatic loading of complicated properties" - which would have to be customizable...and then you'd end up with C#.
Upvotes: 0