使用故事板作为计时器有什么意义?
我见过一些使用 StoryBoard 作为 Timer 的代码示例,例如:
void Update()
{
if (_sb == null)
{
_sb = new Storyboard();
_sb.Completed += _sb_Completed;
_sb.Duration = new Duration(TimeSpan.FromSeconds(1));
}
if (_sb_completed)
{
_sb.Begin();
_sb_completed = false;
}
}
void _sb_Completed(object sender, EventArgs e)
{
PerformUpdate();
_sb_completed = true;
}
Storyboard 在某些时候比 Timer 更好吗?人们为什么使用它?
PS 问题与 Silverlight 和/或 WPF 有关。
I've seen some examples of code where StoryBoard is used as Timer, such as:
void Update()
{
if (_sb == null)
{
_sb = new Storyboard();
_sb.Completed += _sb_Completed;
_sb.Duration = new Duration(TimeSpan.FromSeconds(1));
}
if (_sb_completed)
{
_sb.Begin();
_sb_completed = false;
}
}
void _sb_Completed(object sender, EventArgs e)
{
PerformUpdate();
_sb_completed = true;
}
Is Storyboard at some point better than Timer? Why do people use it?
P.S. Question is related to Silverlight and/or WPF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Storyboard 与 DispatcherTimer 类似,在 UI 线程上运行。因此,无论哪种情况,您都不会看到跨线程异常。
您可以使用 Storyboard 而不是 DispatcherTimer,因为 Storyboard 具有更高的优先级。
但我不确定 Timer 对象本身,因为我从未真正使用它来支持 Storyboard 或 DispatcherTimer。
A Storyboard, like a DispatcherTimer, runs on the UI thread. So in either case you will never see a cross thread exception.
You can use a Storyboard over a DispatcherTimer because the Storyboard has a higher priority.
But im not sure about the Timer object itself as I've never really used it in favor of the Storyboard or DispatcherTimer.
使用
Storyboard
与使用标准System.Threading.Timer
不同。Storybroad
在主线程上运行,因此Completed
甚至可以操作 UI 元素而不会出现跨线程异常。标准Timer
回调不在 UI 线程上运行,因此需要额外的帮助来操作 UI 元素。然而,正如 Mark 指出的,如果真正需要的只是延迟,那么 DispatcherTimer 将是更直观的选择。与
DispatcherTimer
的区别在于,它被设计为定期调用其Tick
事件,而Storyboard
只会在以下时间调用Completed
每次调用Begin
最多一次。可以通过在第一次发生Tick
事件时调用其Stop
方法来以这种方式使用DispatcherTimer
。Using a
Storyboard
is different from using a standardSystem.Threading.Timer
. TheStorybroad
operates on the main thread hence theCompleted
even can manipulate the UI elements without getting cross thread exceptions. The standardTimer
callback doesn't run on the UI thread and will therefore need additional help to manipulate UI elements.However as Mark points out if all that is really needed is a delay then a
DispatcherTimer
would be the more intuative choice. The difference withDispatcherTimer
is that its designed to invoke itsTick
event regularly whereas theStoryboard
will only callCompleted
at most once for each call toBegin
. ADispatcherTimer
can be used in this way by calling itsStop
method in the firstTick
event occurance.