繁体   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