Silverlight Tip of the Day #16 - StoryBoard versus DispatcherTimer for Animation and Game Loops.
When it comes to animation and game loops, it seems the overall consent is that using an empty StoryBoard is currently the best, most efficient way to go.
From my research, the reasons why are as follows:
- The StoryBoard is handled on a separate thread that is not affected by the UI thread which the DispatcherTimer is on.
- The DispatcherTimer is a lower resolution timer than the timer behind the Storyboard class, which causes loss in fidelity.
- The Storyboard execution is more stable across the different supported OS’s and web browsers.
Given that, let’s take a look at how it can be done. In the example below, we create a StoryBoard timer and increment and display a count variable that represents the number of times the MainGameLoop was called. I have set my duration between calls to be zero milliseconds but you will want to change this to whatever best fits your animation story.
Page.xaml.cs:
namespace SilverlightApplication8
{
public partial class Page : UserControl
{
Storyboard _gameLoop = new Storyboard();
int count = 0;
public Page()
{
InitializeComponent();
_gameLoop.Duration = TimeSpan.FromMilliseconds(0);
_gameLoop.Completed += new EventHandler(MainGameLoop);
_gameLoop.Begin();
}
void MainGameLoop(object sender, EventArgs e)
{
// Add any game logic/animation here.
// Example:
myTextbox.Text = count.ToString();
count++;
// Continue storyboard timer
_gameLoop.Begin();
}
}
}
Page.xaml:
<UserControl x:Class="SilverlightApplication8.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="myTextbox">Display Counter</TextBlock>
</Grid>
</UserControl>
Thank you,
--Mike Snow
Subscribe in a reader