0

I m doing image processing for Win Phone, using visual studio 2010. In order to let a a picture displayed for 2 seconds (like slide show), the following class is called

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();
            } 
        }
    }
}

It is called in this way:

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

Because the Application.DoEvents(); is claimed as an error: 'System.Windows.Application' does not contain a definition for 'DoEvents' . So I deleted that code block

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

After compile and run the program, it shows resume ...
How could I correct this? Thanks

4

2 回答 2

2

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

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

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

于 2013-02-07T21:48:09.210 回答
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
}

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

于 2013-02-07T21:55:48.190 回答