WPF: Pattern for high cost initialization objects?

Status
Not open for further replies.

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
So, I've got a subclass of ModelVisual3D that generates a 3d mesh, normals and triangle indices for a cylinder with subtractive voids and am doing some "low hanging fruits" optimizations.

One item I want to address is that the mesh is currently always generated twice (or more), unless it uses 100% default geometry values, because in order to guarantee the mesh is created before being shown on screen, I have to generate the default values before leaving the constructor.
I'd like to figure out a non-hack pattern to make the objects instantiate no more than once per time they are displayed on screen.

Thus far, I have implemented ISupportInitialize so that I can change multiple values without re-generating at each change, but that doesn't get rid of the initial generate in the constructor if it isn't needed.

Ideally, there would be some way I could execute code just before the ViewPort3D object tries to render it to lazily generate the mesh/indices just prior to rendering, thus guaranteeing a single generation per render. ModelVisual3D doesn't seem to have any hookable events or overridable events to do this. Ideas?
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Pont":3qleczm2 said:
I never even realized that existed. However, I don't see how that could work for me, because (it seems to me) it would initialize as soon as I referenced it to set the properties on it.

Is there a way around that?

BTW, the least hack-ish solution I've been able to think of is to manually make an .EnsureGenerated() method on my objects and override the OnVisualParentChanged method to call it.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I'm bemused something (possible multiple things) either properties get/set or methods on your class trigger the generation of the mesh.

Simply take the code that does the generation, put it in a delegate (simplest is put it in a method so it's nice and easy to debug).
Make a private readonly instance field of Lazy<WhateverTheMeshYouCreatesTypeIs> and give the constructor the delegate that points to your instance method.
Anywhere in your class you were building the mesh instead reference the Value property on the lazy instance.

Job done.
 
Status
Not open for further replies.