Wednesday, September 7, 2011

Control Lifecycle Gotcha's in Silverlight

I've come acrosss some more "fun" in Silverlight.  One of the most irritating (and not very well documented) pieces involves the tear-down and destruction of your controls.  Creation of controls is pretty simple, with a few caveats.

Control Creation

When a control or page is created in Silverlight, if the child controls are not visible, they are not "created."  Rather, they are created when they become visible.  For instance, if you have a Container control of some kind (Grid, etc) that is Collapsed, all of the child controls will not be created until it becomes visible.  Given how the rendering/layout engine works in WPF and Silverlight, this kind of makes sense -- only worry about what is visible.

Control Teardown and Destruction

The Unloading event occurs in a different order.

This is the most irritating part for me, as a developer.  Primarily because it doesn't make a whole lot of sense to me and is rather different compared to other frameworks.

Let's start with what we would think should happen, normally.  Supposing you had controls each in a hierarchy of:

A is the parent of B, which is the parent of C.

You would think C gets Unloaded first, then B, then A.

It's the exact opposite.

A is Unloaded, then B, then C.

If you have something, for instance, at point B that needs to be taken care of before C, you'll have some very frustrating issues ahead of you.  For example, C may consume resources that are created in B (such as a service).  Suppose the control is closed, B will attempt to clean up its resources before C does (assuming you've built your controls cleanly).  So, if C is still trying to access the resource created at the scope of B...  C will blow up with all kinds of exceptions.

Finalizers are called upon Application exit.

Not much to be said here -- whereas WPF and WinForms call finalizers generally as soon as the references disappear, Silverlight nukes them upon Application exit.  So, if you want to free up resources, you need to do that beforehand.

In Closing

In short, writing Silverlight is a bit more complicated and doesn't handle things quite as easily as other frameworks we're used to.  However, knowing the afore mentioned, you should be able to make your code cleaner and more efficient.

No comments:

Post a Comment