Channel Directions in Visual Basic .NET

Visual Basic .NET doesn’t have a direct equivalent to Go’s channels, so we’ll use a shared queue and locks to simulate the behavior. We’ll use the ConcurrentQueue class from the System.Collections.Concurrent namespace for thread-safe operations.

Imports System
Imports System.Collections.Concurrent
Imports System.Threading

Module ChannelDirections
    ' This Ping function only accepts a queue for sending values.
    ' It would be a compile-time error to try to receive from this queue.
    Sub Ping(pings As ConcurrentQueue(Of String), msg As String)
        pings.Enqueue(msg)
    End Sub

    ' The Pong function accepts one queue for receives (pings)
    ' and a second for sends (pongs).
    Sub Pong(pings As ConcurrentQueue(Of String), pongs As ConcurrentQueue(Of String))
        Dim msg As String = ""
        While Not pings.TryDequeue(msg)
            Thread.Sleep(10) ' Small delay to avoid busy waiting
        End While
        pongs.Enqueue(msg)
    End Sub

    Sub Main()
        Dim pings As New ConcurrentQueue(Of String)()
        Dim pongs As New ConcurrentQueue(Of String)()

        Ping(pings, "passed message")
        Pong(pings, pongs)

        Dim result As String = ""
        While Not pongs.TryDequeue(result)
            Thread.Sleep(10) ' Small delay to avoid busy waiting
        End While
        Console.WriteLine(result)
    End Sub
End Module

When using queues as function parameters, you can specify if a queue is meant to only send or receive values. This specificity increases the type-safety of the program.

The Ping function only accepts a queue for sending values. It would be a compile-time error to try to receive from this queue.

The Pong function accepts one queue for receives (pings) and a second for sends (pongs).

In the Main function, we create two ConcurrentQueue instances to simulate the behavior of channels. We then call Ping and Pong functions, and finally print the result.

To run the program, save it as ChannelDirections.vb and use the Visual Basic compiler:

$ vbc ChannelDirections.vb
$ ChannelDirections.exe
passed message

This example demonstrates how to use queues to simulate channel-like behavior in Visual Basic .NET, providing a way to safely pass messages between different parts of a program.