System.timers.timer - 无法在经过时间的情况下更新标签

时间:2012-10-08 12:08:22

标签: multithreading timer thread-safety

我想在Windows窗体上显示Label控件上的时间。 因为我正在使用System.Timers.timer但无法使用按钮点击事件的已用时间更新Label。

例如

Private Shared mtimer As System.Timers.Timer

Private Sub btnprocess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnprocess.Click

'Counter to Calculate time as Process Starts
 mDate = Date.Now
 ''Create a timer with  second interval
 mtimer = New System.Timers.Timer()
 ''Hook the Elapsed event
 **AddHandler mtimer.Elapsed, AddressOf Processtick**
 mtimer.Start()
'set the interval 1 second 
 mtimer.Interval = 1000
 mtimer.Enabled = True

 ''Some functions 

   end sub 

Private Sub Processtick(ByVal source As Object, ByVal e As ElapsedEventArgs)

Dim ts As TimeSpan = DateTime.Now.Subtract(mDate)
lblelapsed.Text = ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds

End sub

尝试上面的代码,但它不起作用, 我想在用户点击处理按钮
时立即更新标签控件上的已用时间 直到按钮点击执行所有功能。

请帮忙。

1 个答案:

答案 0 :(得分:0)

由于System.Timers.Timer在单独的线程上运行,因此无法直接更新GUI。您需要在控件上使用BeginInvoke来转发GUI线程的更新。不幸的是我对vb.net并不熟悉,但你可以在这里找到一个如何做到的例子:http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx