views:

45

answers:

2

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.

+1  A: 

Using a Storyboard is different from using a standard System.Threading.Timer. The Storybroad operates on the main thread hence the Completed even can manipulate the UI elements without getting cross thread exceptions. The standard Timer 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 with DispatcherTimer is that its designed to invoke its Tick event regularly whereas the Storyboard will only call Completed at most once for each call to Begin. A DispatcherTimer can be used in this way by calling its Stop method in the first Tick event occurance.

AnthonyWJones
+1  A: 

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.

AlvinfromDiaspar