geminiyellow 发表于 2013-1-28 19:33:23

#16 StoryBoard vs DispatcherTimer

Silverlight Tip of the Day #16 - StoryBoard versus DispatcherTimer for Animation and Game Loops.
 
在第五章,介绍了如何使用DispatcherTimer来进行周期循环。但是,更好的处理方法是使用下面讨论StoryBoard timer 或者 CompositionTarget.Rendering ,这是新加进SilverLight2的功能。 在第五十章将介绍更多关于CompositionTarget.Rendering的知识。
 
根据作者的研究,StoryboardTimer优于DispatcherTimer的原因如下:

[*]StoryBoard是一个单独的线程,不受UI的影响,DispatcherTimer 受影响。
[*]DispatcherTimer的计数器比Storyboard的计数器精度低。会造成失真。
[*]Storyboard在不同的OS和浏览器上运行更稳定。
基于此,让我们看看应该怎么做。在下面的例子中,我们创建一个StoryBoard timer,一个count变量用来表示被MainGameLoop调用次数。我设置了我的调用和开始动画的间隔duration为0,你可以按你的需求去设置。
 
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> 
页: [1]
查看完整版本: #16 StoryBoard vs DispatcherTimer