1

我正在使用 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();


    }
4

1 回答 1

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.
于 2013-01-30T19:20:25.767 回答