簡體   English   中英

每X秒執行一次C#執行方法,直到滿足條件,然后停止

[英]C# Execute Method every X Seconds Until a condition is met and then stop

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


    }

創建另一個更改計時器的事件處理程序。 像這樣:

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM