Select in Visual Basic .NET
Our program demonstrates the use of Select
in Visual Basic .NET, which allows us to wait on multiple asynchronous operations. This is similar to Go’s select statement, but implemented using the Task
class and async/await pattern in .NET.
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module SelectExample
Async Function Main() As Task
' For our example we'll select across two channels.
Dim c1 As Task(Of String) = Task.Run(Function() DelayedMessage("one", 1000))
Dim c2 As Task(Of String) = Task.Run(Function() DelayedMessage("two", 2000))
' We'll use Select to await both of these values
' simultaneously, printing each one as it arrives.
For i As Integer = 0 To 1
Dim completedTask = Await Task.WhenAny(c1, c2)
If completedTask Is c1 Then
Console.WriteLine("received " & Await c1)
c1 = Task.CompletedTask
ElseIf completedTask Is c2 Then
Console.WriteLine("received " & Await c2)
c2 = Task.CompletedTask
End If
Next
End Function
Private Async Function DelayedMessage(message As String, delay As Integer) As Task(Of String)
Await Task.Delay(delay)
Return message
End Function
End Module
In this example, we’re using Task.Run
to simulate concurrent operations that complete after a specific delay. The DelayedMessage
function represents an asynchronous operation that returns a message after a specified delay.
We use Task.WhenAny
to wait for either of the tasks to complete, which is similar to the select
statement in the original example. When a task completes, we print its result and mark it as completed to prevent it from being selected again.
To run the program:
$ vbc SelectExample.vb
$ mono SelectExample.exe
received one
received two
Note that the total execution time is only about 2 seconds since both the 1 and 2 second delays execute concurrently.
This example demonstrates how to work with multiple asynchronous operations in Visual Basic .NET, providing functionality similar to Go’s select statement.