Timer.Elapsed火灾事件只有一次,我希望每秒一次

Hir*_*ren 3 c# asp.net timer

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);
    }
Run Code Online (Sandbox Code Playgroud)

更新: 我通过在Visual Studio中创建新网站来尝试它.但仍然没有获得success.same问题.现在更新是我在Line中设置Break Point的时候

     TextBoxStopWatch.Text=   Convert.ToString(sw.Elapsed);
Run Code Online (Sandbox Code Playgroud)

文本在那里连续更改但不在TextBox中显示.希望你能理解这一点.

小智 5

Start()你甚至在设置参数之前就打电话了.试试这个:

StopWatchTimer.Interval = 1000; 
StopWatchTimer.AutoReset = true; 
StopWatchTimer.Elapsed += new System.Timers.ElapsedEventHandler(StopWatchTimer_Tick); 
StopWatchTimer.Enabled = true; 
Run Code Online (Sandbox Code Playgroud)

在设置所有Enabled属性true后将属性设置为.(调用Start()方法相当于设置Enabled = true)

此外,不确定您是否知道这一点,但该Timer.Interval属性是以毫秒为单位.所以你Timer.Elapsed每毫秒都要开火.只是一个FYI.