每隔X秒执行C#执行方法直到满足条件然后停止

时间:2013-01-30 19:06:18

标签: c# silverlight timer

我正在使用Silverlight C#按钮点击事件在点击后暂停10秒,然后每隔x秒调用一次方法,直到满足特定条件:x = y或经过秒数> = 60而不冻结UI。

有几个不同的例子。我是C#的新手,我正在努力保持简单。我提出了以下内容,但我没有最初的10秒等待,我需要了解放在哪里,似乎我有一个无限循环。 这是我的代码:

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


    }

1 个答案:

答案 0 :(得分:0)

创建第二个更改计时器的事件处理程序。像这样:

public void StartTimer()
{
    System.Windows.Threading.DispatcherTimer myDispatcherTimer = 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)
{
    // Stop the timer, replace the tick handler, and restart with new interval.
    myDispatchTimer.Stop();
    myDispatchTimer.Tick -= new EventHandler(Initial_Wait);
    myDispatcherTimer.Interval = TimeSpan.FromSeconds(interval); //every x seconds
    myDispatcherTimer.Tick += new EventHandler(Each_Tick);
    myDispatcherTimer.Start();
}

计时器第一次打勾时调用Initial_Wait。该方法停止计时器,将其重定向到Each_Tick,并调整间隔。所有后续刻度都将转到Each_Tick

如果您希望计时器在60秒后停止,请在首次启动计时器时创建Stopwatch,然后在每次打勾时检查Elapsed值。像这样:

修改InitialWait方法以启动Stopwatch。您需要一个类范围变量:

private Stopwatch _timerStopwatch;

void Initial_Wait(object o, EventArgs sender)
{
    // changing the timer here
    // Now create the stopwatch
    _timerStopwatch = Stopwatch.StartNew();
    // and then start the timer
    myDispatchTimer.Start();
}

Each_Tick处理程序中,检查已用时间:

if (_timerStopwatch.Elapsed.TotalSeconds >= 60)
{
    myDispatchTimer.Stop();
    myDispatchTimer.Tick -= new EventHandler(Each_Tick);
    return;
}
// otherwise do the regular stuff.