Tickers in Visual Basic .NET

Our first example demonstrates the use of tickers in Visual Basic .NET. Tickers are used when you want to perform an action repeatedly at regular intervals.

Imports System
Imports System.Threading
Imports System.Threading.Tasks

Module TickerExample
    Sub Main()
        ' Create a CancellationTokenSource to manage the cancellation of the ticker
        Dim cts As New CancellationTokenSource()
        
        ' Create a timer that ticks every 500 milliseconds
        Dim ticker = New Timer(AddressOf TickCallback, Nothing, 0, 500)

        ' Run the ticker for 1600 milliseconds
        Task.Delay(1600).Wait()

        ' Stop the ticker
        cts.Cancel()
        ticker.Dispose()
        Console.WriteLine("Ticker stopped")
    End Sub

    Private Sub TickCallback(state As Object)
        Console.WriteLine($"Tick at {DateTime.Now}")
    End Sub
End Module

In this example, we use the Timer class to create a ticker that fires every 500 milliseconds. The TickCallback method is called each time the timer ticks, printing the current time.

We use Task.Delay to wait for 1600 milliseconds before stopping the ticker. This is equivalent to the time.Sleep function in the original example.

To stop the ticker, we dispose of the Timer object. This is similar to calling Stop() on the ticker in the original code.

When we run this program, the ticker should tick 3 times before we stop it:

Tick at 5/1/2023 10:30:00 AM
Tick at 5/1/2023 10:30:00 AM
Tick at 5/1/2023 10:30:01 AM
Ticker stopped

Note that Visual Basic .NET doesn’t have an exact equivalent to Go’s channels and select statement. Instead, we use the Timer class and a callback method to achieve similar functionality. The CancellationTokenSource is used to manage the cancellation of the ticker, although in this simple example, we don’t directly use it to cancel the timer.