Caliburn Micro 1.1 - windows-phone 7 Performance Tip - Use OnViewReady

02 July 2011

Microsoft have posted up a series of performance considerations when developing Windows Phone apps which any developer should read. There is one section in particular called “Minimize the Code in Constructors and Loaded Events” which you can find here a few sub headings down: http://msdn.microsoft.com/en-us/library/ff967560(v=vs.92).aspx#BKMK_Startup

The recommended code for each view is presented below. Whilst this may make sense, it is messy and begs the question for me of why Microsoft didn’t put this in an override called something like OnViewReady? They instead recommend that developers do their work after OnNavigatedTo which actually isn’t best for performance.

private bool _onNavigatedToCalled = false;

public Page()
{
    InitializeComponent();
    LayoutUpdated += new EventHandler(Page_LayoutUpdated);
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    _onNavigatedToCalled = true;
}

private void Page_LayoutUpdated(object sender, EventArgs e)
{
    if (_onNavigatedToCalled == true)
    {
        _onNavigatedToCalled = false;
        Dispatcher.BeginInvoke(() =>
            {
                // Do your stuff here, in the “future”                    }
            }
        );
    }
}

As usual, Caliburn Micro to the rescue. In the latest version there is now a helpful override for your View Models which inherit from any IViewAware implementation such as our old trusty friend Screen, which is called, you guessed it, OnViewReady!

Simply use this override  in your View Model to conduct all initial heavy lifting when the view is ready (i.e. View’s OnLayoutUpdated fired first time after OnNavigatedTo). Of course the same principles apply here of offloading to background thread (e.g. BackgroundWorker) and marshalling back to UI thread but the key thing is that this is an ideal place to start this work so that the UI appears more responsive.

protected override void OnViewReady(object view)
{
    base.OnViewReady(view);
    // do heavy lifting here.
}
Want to get started?

We would love to help with your next app or game, please do get in touch.