簡體   English   中英

Timer.Elapsed火災事件只有一次,我想每秒鍾

[英]Timer.Elapsed fire event only once,I want it every Second

Timers.Timer創建StopWatch。 我使用Timer.Elapsed來處理在特定時間之后顯示時間的事件。 我將定時器間隔設為1並啟用為真。 我也將AutoReset設為true。 但問題是事件只發射一次。我只在文本框中得到一次時間。如何在TextBox中每隔一秒更改時間。我嘗試所有替代方案但沒有獲得成功...謝謝

    System.Timers.Timer StopWatchTimer = new System.Timers.Timer();
    Stopwatch sw = new Stopwatch();
     public void StopwatchStartBtn_Click(object sender, ImageClickEventArgs e)
    {

        StopWatchTimer.Start();
        StopWatchTimer.Interval = 1;
        StopWatchTimer.Enabled = true;
        StopWatchTimer.AutoReset =true; 
        sw.Start();
        StopWatchTimer.Elapsed += new System.Timers.ElapsedEventHandler(StopWatchTimer_Tick);
    }

    protected void StopWatchStopBtn_Click(object sender, ImageClickEventArgs e)
    {

        TextBoxStopWatch.Text = "00:00:000";
        StopWatchTimer.Stop();
        sw.Reset();
        sw.Stop(); 

    }

    public void StopWatchTimer_Tick(object sender,EventArgs e)
    {           
   TextBoxStopWatch.Text=   Convert.ToString(sw.Elapsed);
    }

更新:我通過在Visual Studio中創建新網站來嘗試它。但仍然沒有獲得success.same問題。 現在更新是我在Line中設置Break Point的時候

     TextBoxStopWatch.Text=   Convert.ToString(sw.Elapsed);

文本在那里連續更改但不在TextBox中顯示。 希望你能理解這一點。

您甚至在設置參數之前調用Start() 嘗試這個:

StopWatchTimer.Interval = 1000; 
StopWatchTimer.AutoReset = true; 
StopWatchTimer.Elapsed += new System.Timers.ElapsedEventHandler(StopWatchTimer_Tick); 
StopWatchTimer.Enabled = true; 

設置所有屬性后,將Enabled屬性設置為true (調用Start()方法相當於設置Enabled = true

此外,不確定您是否知道這一點,但Timer.Interval屬性以毫秒為單位。 所以你每毫秒都會觸發Timer.Elapsed事件。 只是一個FYI。

你不能這樣在網頁上這樣做。

在呈現頁面時,服務器已完成,客戶端已斷開連接。 它不會從您的計時器獲得任何更新。

如果你需要在頁面上有一個計時器顯示一些不斷變化的數字,那么你將不得不通過javascript這樣做。

您還需要考慮到文本框的內容只能由UI線程而不是回調上下文更改。 你是否對回調采取了例外? 查看使用調度程序在主UI線程而不是計時器線程上調用UI更新。

以下適用於我。 我重新安排了一些東西,所以定時器/秒表的設置只設置一次,以避免混淆,並處理UI線程調用。

    System.Timers.Timer timer;
    Stopwatch stopwatch;

    public Form1()
    {
        InitializeComponent();

        timer = new System.Timers.Timer();
        timer.Interval = 1000;
        timer.AutoReset = true;
        timer.Elapsed += new ElapsedEventHandler(TimerElapsed);

        stopwatch = new Stopwatch();
    }

    public void TimerElapsed(object sender, EventArgs e)
    {
        TextBoxStopWatch.Text = Convert.ToString(stopwatch.Elapsed);
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        timer.Start();
        stopwatch.Start();
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        TextBoxStopWatch.Text = "00:00:000";
        timer.Stop();
        stopwatch.Reset();
        stopwatch.Stop();
    }

暫無
暫無

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

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