gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:49:40 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com