Timers in Visual Basic .NET
Our first example demonstrates the use of timers in Visual Basic .NET. Timers allow us to execute code at a specific point in the future or repeatedly at some interval.
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Program
Sub Main()
' Timers represent a single event in the future. We set up
' a timer that will trigger after 2 seconds.
Dim timer1 = New Timer(AddressOf Timer1Callback, Nothing, 2000, Timeout.Infinite)
' Wait for the timer to fire
Thread.Sleep(2100)
' If you just wanted to wait, you could have used
' Thread.Sleep. One reason a timer may be useful is
' that you can cancel the timer before it fires.
' Here's an example of that.
Dim timer2 = New Timer(AddressOf Timer2Callback, Nothing, 1000, Timeout.Infinite)
' Stop the timer before it has a chance to fire
timer2.Change(Timeout.Infinite, Timeout.Infinite)
Console.WriteLine("Timer 2 stopped")
' Give timer2 enough time to fire, if it ever
' was going to, to show it is in fact stopped.
Thread.Sleep(2000)
' Dispose the timers
timer1.Dispose()
timer2.Dispose()
End Sub
Private Sub Timer1Callback(state As Object)
Console.WriteLine("Timer 1 fired")
End Sub
Private Sub Timer2Callback(state As Object)
Console.WriteLine("Timer 2 fired")
End Sub
End Module
In this example, we create two timers:
The first timer (
timer1
) is set to fire after 2 seconds. We wait for it to fire usingThread.Sleep
.The second timer (
timer2
) is set to fire after 1 second, but we stop it before it has a chance to fire.
Here’s what the output would look like:
Timer 1 fired
Timer 2 stopped
The first timer fires after approximately 2 seconds, but the second timer is stopped before it has a chance to fire.
In Visual Basic .NET, we use the System.Threading.Timer
class to create timers. The Timer
constructor takes a callback method, a state object (which we don’t use in this example, so we pass Nothing
), the delay before the timer starts, and the period for repeating (we use Timeout.Infinite
for one-time timers).
To stop a timer, we use the Change
method with Timeout.Infinite
for both the due time and period. This effectively stops the timer from firing.
Remember to dispose of timers when you’re done with them to free up system resources.
This example demonstrates basic timer usage in Visual Basic .NET, including creating, firing, and stopping timers.