如何仅用代码构建计数器变量



我想创建一个以毫秒为单位从0开始计数的变量我不想使用工具箱中的计时器,而是用代码构建它。到目前为止,我声明了一个计时器对象,但是我如何将它绑定到一个事件,该事件可以将时间转换为计数器并将其附加到变量中?

看下面我尝试了什么,但没有成功

Imports System.Timers
Public Class Counter
Property Count As Integer
Private Sub Counter_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Count = Counter()
Console.WriteLine(Count)
End Sub
Public Function Counter() As Integer
' Create timer
Dim timer As Timer = New Timer()
timer.Interval = 1000
'AddHandler timer.Elapsed, AddressOf TimerEvent
timer.AutoReset = True
timer.Enabled = True
Return Integer.Parse(timer.ToString())
End Function
Private Sub CountEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)
'Console.WriteLine("Event Raised at {0:HH:mm:ss.fff}", e.SignalTime)
'Console.WriteLine("Count Miliseconds {0:fff}", e.SignalTime) ' count milisecond
Console.WriteLine("Count Seconds {0:ss}", e.SignalTime) ' count milisecond
End Sub
End Class

希望我下面的代码能对你有所帮助。它将在控制台应用程序中按原样运行,但你只需要提取Counter类。

Imports System.Timers
Module Module1
Dim oCounter As Counter
Sub Main()
oCounter = New Counter(1000)
AddHandler oCounter.Count, AddressOf Counter_Count
Console.WriteLine("You can press any key to quit after 10,000 milliseconds.")
oCounter.StartCounter()
While oCounter.TotalMillisecondsPassed < 10000
Console.ReadKey()
End While
End Sub
Sub Counter_Count(Sender As Object, TotalMillisecondsPassed As Long)
Console.WriteLine(TotalMillisecondsPassed & " milliseconds passed since: " & oCounter.StartTime.ToString("dd/MM/yyyy HH:mm:ss:fff"))
End Sub
' A class to keep track of the number of milliseconds passed since the 
' Timer was initiated and to raise an event every x number of milliseconds
Private Class Counter
' The time the Counter was started
Public ReadOnly Property StartTime As Date
Get
Return MyStartTime
End Get
End Property
' The total number of milliseconds that have passed
Public ReadOnly Property TotalMillisecondsPassed As Long
Get
Return (Date.Now - MyStartTime).TotalMilliseconds
End Get
End Property
' The event is raised each time the interval has passed    
Public Event Count(Sender As Object, TotalMillisecondsPassed As Long)
Private MyStartTime As Date
Private oTimer As Timer
' The interval between Count events
Public Sub New(IntervalInMillisenconds As Integer)
oTimer = New Timer(IntervalInMillisenconds)
AddHandler oTimer.Elapsed, AddressOf TimerElapsed
oTimer.AutoReset = True
End Sub
' Starts the counter
Public Sub StartCounter()
MyStartTime = Date.Now()
oTimer.Start()
End Sub
' Stops the counter
Public Sub StopCounter()
oTimer.Stop()
End Sub
' Handles the internal event of the timer elapsing
Private Sub TimerElapsed(ByVal source As Object, ByVal e As ElapsedEventArgs)
RaiseEvent Count(Me, TotalMillisecondsPassed)
End Sub
End Class

End Module

我解决了

Dim Counter As Integer

Private Sub TimerEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)
' Count Up
If 1 <> 2 Then
Counter = Counter + 1
End If
Console.WriteLine("Count Up: " & Counter)
End Sub

最新更新