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.
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:
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.