簡體   English   中英

在設置的時間間隔后如何停止Timer對象?

[英]How to stop a Timer object after a set interval of time?

我已經從文本框中為日期時間變量分配了一個字符串值。它的目的是用作一個標志,告訴myTimer對象在到達workDt(日期時間變量)中存儲的時間時停止。

我嘗試過的當前實現如下所示,其中設置了if..else語句來檢查計時器的當前時間是否等於在文本框中輸入的時間,但不會觸發計時器停止。

我在'if'語句上設置了一個斷點,並且時間值存儲在workDt中,但沒有觸發計時器停止。

誰能看到我的實現中的缺陷或就替代解決方案提供任何建議?

private void startBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {


            string wrkString;
            string rstString; 


            //Assign text box time string to string variables.
            wrkString = wrkTbx.Text;
            rstString = restTbx.Text;


            //Assign text box string value to a date time variable.

            DateTime workDt = DateTime.ParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
            DateTime restDt = DateTime.ParseExact(rstString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);


            StopGoCvs.Background = new SolidColorBrush(Colors.Green);
            hornElmt.Play();
            //    // set up the timer
            myTimer = new DispatcherTimer();
            myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
            myTimer.Tick += myTimer_Tick;

            //tell timer to stop when it has reached the allocated work time.
            if(myTimer.Interval != workDt.TimeOfDay)
            {
                // start both timers
                myTimer.Start();
                myStopwatch.Start();

            }
            else
            {
                myTimer.Stop();
                myStopwatch.Stop();

            }



        }

使計時器對象成為全局對象,以便類中的所有方法或事件都可以訪問,然后啟動計時器給每次到達的時間都分配一個事件,然后在該事件上有條件地檢查時間是否達到您的預期時間,然后停止計時器。

將時間間隔設置為: myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); 表示您將時間間隔設置為1ms,因此無法滿足以下條件:

myTimer.Interval == workDt.TimeOfDay

永遠被滿足

您正在尋找的更多是秒表而不是計時器。

暫無
暫無

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

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