Feed Icon  

Contact

  • Bryant Likes
  • Send mail to the author(s) E-mail
  • twitter
  • View Bryant Likes's profile on LinkedIn
  • del.icio.us
Get Microsoft Silverlight
by clicking "Install Microsoft Silverlight" you accept the
Silverlight license agreement

Hosting By

Hot Topics

Tags

Open Source Projects

Archives

Ads

Faking the Initialized Event in Silverlight

Posted in Silverlight at Tuesday, March 24, 2009 9:24 AM Pacific Standard Time

This is another nugget of gold gleaned from the Climbing Mt Avalon workshop, although I believe this one came from Jonathan Russ. He was talking about a bunch of threading tricks in WPF and showed how if you wanted to run some code after everything was initialized you could use the BeginInvoke method of the Dispatcher object. Since there are many places in my code where I want to execute something when the control loads, but only once (since the loaded event gets fired whenever the object gets re-added to the visual tree) I end up writing a lot of code like:

public partial class Page : UserControl
{
    private bool initialized = false;

    public Page()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(Page_Loaded);
    }

    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        if (!initialized)
        {
            // do some initialization work
            initialized = true;
        }
    }

}

This works, but it isn’t perfect and there seems to be a lot of issues with the timing of the loaded event. So based on what Jonathan was saying, you could instead just put a call into BeginInvoke in the contructor like so:

public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();
        Dispatcher.BeginInvoke(Initialized);
    }

    private void Initialized()
    {
        // do some initialization work
    }
}

So what is this actually doing? BeginInvoke puts a message in the message pump that is running under the covers of everything (note: I’m not a C++ programming so I don’t really fully understand message pumps so this is an over simplification). Because it is last in line in the queue of messages to process, it gets executed after all the other initialization code which has already lined up. If you debug this you will see it actually gets called after the Loaded event gets called. However, this code is the first thing to execute once everything has been loaded and setup which is usually when I want my code to execute.

So this is a much better way to handle initialization code since you aren’t adding event handlers that really only need to fire once and it executes once everything is fully initialized.

Tuesday, March 24, 2009 2:56:27 PM (Pacific Standard Time, UTC-08:00)
Nice tip mate. Thumbs up
Tuesday, March 24, 2009 10:16:48 PM (Pacific Standard Time, UTC-08:00)
Could you not just have a "Setup()" method or something? And call it from the contructor, PageLoad or wherever you like...?
Comments are closed.