我在 VB.NET 中的计时器丢失一秒 [英] My timer in VB.NET is Losing one second
问题描述
我使用 DateTimePicker 来选择一个 dateTime 值并查看我有多少时间直到它为零:
I use a DateTimePicker to pick a dateTime value and see how much time I have until it is zero:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
timeInSeconds = (DateTimePicker1.Value.Subtract(System.DateTime.Now)).ToString
'RichTextBox1.Text = RichTextBox1.Text + vbTab + timeInSeconds.ToString
timeInSeconds = timeInSeconds.Substring(0, timeInSeconds.LastIndexOf("."))
End Sub
上面的 RichTextbox 显示我大约每 30 秒丢失一秒钟:
The RichTextbox above shows that I loose a second at about each 30 seconds:
23:59:47.4060217
23:59:46.3939638
23:59:45.3799058
23:59:44.3648477
23:59:43.3517898
23:59:42.3377318
23:59:41.3236738
23:59:40.3096158
23:59:39.2955578
23:59:38.2814998
23:59:37.2674418
23:59:36.2533838
23:59:35.2393258
23:59:34.2242677
23:59:33.2112098
23:59:32.1981518
23:59:31.1830938
23:59:30.1690358
23:59:29.1549778
23:59:28.1409198
23:59:27.1268618
23:59:26.1128038
23:59:25.0997458
23:59:24.0856878
23:59:23.0716298
23:59:22.0575718
23:59:21.0435138
23:59:20.0284558
23:59:19.0143978
**23:59:18.0013398
23:59:16.9872818**
所以使用
timeInSeconds = timeInSeconds.Substring(0, timeInSeconds.LastIndexOf("."))
从 23:59:18 到 23:59:16
it goes from 23:59:18 to 23:59:16
为什么会这样?我做错了什么?是时候
Why is that so? What I do wrong? Is it the time that
(DateTimePicker1.Value.Subtract(System.DateTime.Now)).ToString
发生在我失去的地方?
计时器设置为每秒更改一次.
我该怎么做才能获得正确的结果?
What Can I do to have the right results?
提前致谢!
推荐答案
尽量不要直接附加文本,而是将结果连接到 tmp 字符串中.之后将 tmp 分配给 textbox1.text.
Try not appending the text directly, but rather concatenate the result in a tmp string. After that assign tmp to textbox1.text.
我曾经遇到过每次 forloop 迭代都必须修改文本框以显示一个十六进制字节的情况,当我转向之前的方法时,结果令人印象深刻.
I've been in a situations where I must modify a textbox every forloop iteration to display one byte in hex, the result was impressive when I shift to the previous methodology.
试试看.
来自评论:
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Dim timeInSeconds = (DateTimePicker1.Value.Subtract(System.DateTime.Now)).ToString
'RichTextBox1.Text = RichTextBox1.Text + vbTab + timeInSeconds.ToString
timeInSeconds = timeInSeconds.Substring(0, timeInSeconds.LastIndexOf("."))
TextBox1.Text &= timeInSeconds & vbNewLine
End Sub
我在 1000 毫秒计时器中测试了此代码,没有问题.
I tested this code in a 1000 milisec timer and there's no problem.
这篇关于我在 VB.NET 中的计时器丢失一秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!