Silverlight Tip of the Day #50 – Main Game Loop Revisited!
In the recent release of Silverlight 2 RC0 there is a new event that fires once before the rendering of each frame in your browser. This rendering event is routed to the specified event handler after animation and layout have been applied to the composition tree. In addition, if changes to the visual tree force updates to the composition tree, your event handler is also called.
So, instead of having to use the DispatchTimer or Storyboard Timer, you can now use this new event for your MainGameLoop(). To add the event all you have to do is make a call to:
CompositionTarget.Rendering += new EventHandler(MainGameLoop);
Looking back at our Snowflake demo, the following code was used to create a Storyboard timer to run the main loop:
Storyboard _snowflakeTimer = new Storyboard();
public Page()
{
InitializeComponent();
_snowflakeTimer.Duration = TimeSpan.FromMilliseconds(0);
_snowflakeTimer.Completed += new EventHandler(SnowFlakeTimer);
_snowflakeTimer.Begin();
}
private void SnowFlakeTimer(object sender, EventArgs e)
{
MoveSnowFlakes();
CreateSnowFlakes();
}
The new way to do it would be:
public Page()
{
InitializeComponent();
CompositionTarget.Rendering += new EventHandler(SnowFlakeTimer);
}
private void SnowFlakeTimer(object sender, EventArgs e)
{
MoveSnowFlakes();
CreateSnowFlakes();
}
Thank you,
--Mike Snow
Subscribe in a reader