Non Blocking Channel Operations in Visual Basic .NET

Basic sends and receives on channels are blocking. However, we can use Select with a Case Else clause to implement non-blocking operations, similar to multi-way non-blocking selects.

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

Module NonBlockingChannelOperations
    Sub Main()
        Dim messages As New BlockingCollection(Of String)()
        Dim signals As New BlockingCollection(Of Boolean)()

        ' Here's a non-blocking receive. If a value is
        ' available in 'messages' then it will be retrieved,
        ' otherwise it will immediately take the 'Case Else' case.
        Select Case True
            Case messages.TryTake(Nothing, 0)
                Console.WriteLine("received message: " & Nothing)
            Case Else
                Console.WriteLine("no message received")
        End Select

        ' A non-blocking send works similarly. Here 'msg'
        ' cannot be sent to the 'messages' collection, because
        ' the collection has no space and there is no receiver.
        ' Therefore the 'Case Else' case is selected.
        Dim msg As String = "hi"
        Select Case True
            Case messages.TryAdd(msg, 0)
                Console.WriteLine("sent message: " & msg)
            Case Else
                Console.WriteLine("no message sent")
        End Select

        ' We can use multiple 'Case' statements above the 'Case Else'
        ' clause to implement a multi-way non-blocking select. 
        ' Here we attempt non-blocking receives on both 'messages' and 'signals'.
        Dim receivedMsg As String = Nothing
        Dim receivedSignal As Boolean
        Select Case True
            Case messages.TryTake(receivedMsg, 0)
                Console.WriteLine("received message: " & receivedMsg)
            Case signals.TryTake(receivedSignal, 0)
                Console.WriteLine("received signal: " & receivedSignal)
            Case Else
                Console.WriteLine("no activity")
        End Select
    End Sub
End Module

To run the program, save it as NonBlockingChannelOperations.vb and use the VB.NET compiler:

$ vbc NonBlockingChannelOperations.vb
$ mono NonBlockingChannelOperations.exe
no message received
no message sent
no activity

In this Visual Basic .NET version, we use BlockingCollection(Of T) to simulate channels. The TryTake and TryAdd methods with a timeout of 0 are used to implement non-blocking operations. The Select Case True structure is used to mimic the behavior of Go’s select statement.

Note that this is not an exact equivalent of the Go code, as Visual Basic .NET doesn’t have built-in channel-like constructs. However, this code demonstrates a similar concept of non-blocking operations on collections.