本文介绍了Silverlight(桌面不是手机)循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Silverlight桌面应用程序,它在单击按钮后启动计时器。定时器等待10秒,然后,它将重置定时器,每5秒循环一次。



如何在60秒后停止计时器?有人推荐了StopWatch,但它在Silverlight Desktop中不可用。



这是我的代码有效,但60秒后它不会停止:



谢谢!





I have a Silverlight Desktop Application which starts a timer after a button is clicked. The Timer Waits for 10 seconds, then, it will reset the timer to loop every 5 seconds.

How do I stop the timer after 60 seconds have elapsed? Someone recommended the StopWatch, but it''s not available in Silverlight Desktop.

Here is my code that works, but it does not stop after 60 seconds:

Thank you!


public void StartTimer()
        {
            System.Windows.Threading.DispatcherTimer myDispatchTimer = new System.Windows.Threading.DispatcherTimer();
            myDispatchTimer.Interval = TimeSpan.FromSeconds(10); // initial 10 second wait
            myDispatchTimer.Tick += new EventHandler(Initial_Wait);
            myDispatchTimer.Start();
        }
        void Initial_Wait(object o, EventArgs sender)
        {
            System.Windows.Threading.DispatcherTimer myDispatchTimer = new System.Windows.Threading.DispatcherTimer();
            // Stop the timer, replace the tick handler, and restart with new interval.
            myDispatchTimer.Stop();
            myDispatchTimer.Tick -= new EventHandler(Initial_Wait);
            myDispatchTimer.Interval = TimeSpan.FromSeconds(5); //every x seconds
            myDispatchTimer.Tick += new EventHandler(Each_Tick);
            myDispatchTimer.Start();
        }

        // Counter:
        int i = 0;
        // Ticker
        void Each_Tick(object o, EventArgs sender)
        {
            GetMessageDeliveryStatus(messageID, messageKey);
            textBlock1.Text = "Seconds: " + i++.ToString();
        }

推荐答案

private System.Windows.Threading.DispatchTimer timer = new System.Windows.Threading.DispatcherTimer();
private bool firstRun = true;
private DateTime startTime = DateTime.MinValue;

private void StartTimer()
{
    startTime = DateTime.Now;
    timer.Interval = TimeSpan.FromSeconds(10);
    timer.Tick += new EventHandler(timer_Tick);
    timer.Start();
}

void timer_Tick(object sender, EventArgs e)
{
    if (firstRun)
    {
        timer.Interval = TimeSpan.FromSeconds(5);
        firstRun = false;
    }
    if (DateTime.Now.Subtract(startTime).TotalSeconds > 60)
    {
        timer.Stop();
    }
    else
    {
        var t = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
        {
            // ...do stuff that takes a while....
        }));
        t.Start();
        // ...or do stuff that runs quickly....
    }
}


这篇关于Silverlight(桌面不是手机)循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:59