c# - Timer.Elapsed 触发事件只有一次,我想要每秒

标签 c# asp.net timer

Timers.Timer 来创建秒表。我使用 Timer.Elapsed 来处理在特定时间后显示时间的事件。我给定时器间隔 1 并启用为真。我还将 AutoReset 设置为 true。但问题是事件只触发一次。我只在文本框中获得一次时间。如何每秒更改文本框中的时间。我尝试了所有替代方案但没有成功......谢谢

    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 中创建新网站来尝试。但仍然没有成功。同样的问题。现在更新是当我在行中设置断点

     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 事件。仅供引用。

关于c# - Timer.Elapsed 触发事件只有一次,我想要每秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8792944/

相关文章:

java - 如何选择时间/日期并将其放入计时器任务中?

iOS 每天运行一次代码

c# - 网络 MVC : How do I get virtual url for the current controller/view?

c# - Linq过滤属性的 setter/getter

java - 使用计时器在 JFreeChart 上闪烁 XYImageAnnotation

c# - 在 ASP 中打开并读取 txt 文件

ASP.NET MVC + EF 4.1 分层、模型、 View 模型

c# - 将数据表保存为用户设置

c# - 一对零或一关系的 Entity Framework (EF) 代码优先级联删除

c# - 用户登录后如何隐藏登录和注册按钮?