winphone让代码等待2秒DispatcherTimer

时间:2013-02-07 20:52:03

标签: c# windows-phone-7 timer

我使用visual studio 2010为Win Phone进行图像处理。 为了让图片显示2秒钟(如幻灯片放映),以下类称为

namespace photoBar
{
    public class WaitTwoSeconds
    {
        DispatcherTimer timer = new DispatcherTimer();
        public bool timeUp = false;

        // This is the method to run when the timer is raised. 
        private void TimerEventProcessor(Object myObject,
                                                EventArgs myEventArgs)
        {
            timer.Stop();
            timeUp = true;
        }

        public WaitTwoSeconds()
        {
            /* Adds the event and the event handler for the method that will 
               process the timer event to the timer. */
            timer.Tick += new EventHandler(TimerEventProcessor);

            // Sets the timer interval to 2 seconds.
            timer.Interval = new TimeSpan(0, 0, 2); // one second
            timer.Start();

            //// Runs the timer, and raises the event. 
            while (timeUp== false)
            {
                // Processes all the events in the queue.
                Application.DoEvents();
            } 
        }
    }
}

以这种方式调用:

        WaitTwoSeconds waitTimer = new WaitTwoSeconds();
        while (!waitTimer.timeUp)
        {
        }

因为Application.DoEvents();被声称为错误:'System.Windows.Application'不包含'DoEvents'的定义。所以我删除了那个代码块

        while (timeUp== false)
        {
            // Processes all the events in the queue.
            Application.DoEvents();
        } 

编译并运行程序后,显示简历...
我怎么能纠正这个?感谢

2 个答案:

答案 0 :(得分:2)

使用Reactive Extensions(参考Microsoft.Phone.Reactive)可以更轻松地完成此操作:

Observable.Timer(TimeSpan.FromSeconds(2)).Subscribe(_=>{
    //code to be executed after two seconds
});

请注意,代码不会在UI线程上执行,因此您可能需要使用Dispatcher。

答案 1 :(得分:0)

拥抱多线程。

public class WaitTwoSeconds
{
    DispatcherTimer timer = new DispatcherTimer();
    Action _onComplete;

    // This is the method to run when the timer is raised. 
    private void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs)
    {
        timer.Stop();
        _onComplete();
    }

    public WaitTwoSeconds(Action onComplete)
    {
        _onComplete = onComplete;
        timer.Tick += new EventHandler(TimerEventProcessor);
        timer.Interval = new TimeSpan(0, 0, 2); // one second
        timer.Start();

    }
}

并在您的代码中

private WaitTwoSeconds waitTimer;
private void SomeButtonHandlerOrSomething(
    object sender, ButtonClickedEventArgsLol e)
{    
    waitTimer = new WaitTwoSeconds(AfterTwoSeconds);
}

private void AfterTwoSeconds()
{
    // do whatever
}

这种设计并不是那么好,但它应该让您清楚地了解多线程的工作原理。如果您不是做某事,那么不会阻止