Freigeben über


Silverlight Tip of the Day #16 - StoryBoard versus DispatcherTimer for Animation and Game Loops.

In Tip of the Day #5 I discussed how to use the DispatcherTimer for your main game loop. However, a better approach may be to use the StoryBoard timer as discussed here or the CompositionTarget.Rendering event which was recently added to Silverlight 2. Check out Tip of the Day #50 for more info on using the CompositionTarget.Rendering event for your main game loop.

From my research, the reasons the StoryboardTimer is better than the DispatcherTimer is as follows:

  1. The StoryBoard is handled on a separate thread that is not affected by the UI thread which the DispatcherTimer is on.
  2. The DispatcherTimer is a lower resolution timer than the timer behind the Storyboard class, which causes loss in fidelity.
  3. 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="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="https://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

Comments