Channel Synchronization in Visual Basic .NET

Our example demonstrates how to use channels for synchronization between different parts of a program. In Visual Basic .NET, we’ll use the Task class and a ManualResetEventSlim to achieve similar functionality.

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

Module ChannelSynchronization
    ' This is the function we'll run in a separate task. The
    ' doneEvent will be used to notify the main thread that 
    ' this function's work is done.
    Sub Worker(doneEvent As ManualResetEventSlim)
        Console.Write("working...")
        Thread.Sleep(1000) ' Simulate work
        Console.WriteLine("done")

        ' Signal that we're done
        doneEvent.Set()
    End Sub

    Sub Main()
        ' Create a ManualResetEventSlim to notify when the work is done
        Dim doneEvent As New ManualResetEventSlim(False)

        ' Start a worker task, giving it the event to signal on completion
        Task.Run(Sub() Worker(doneEvent))

        ' Block until we receive a notification from the worker
        doneEvent.Wait()
    End Sub
End Module

To run the program:

$ vbc ChannelSynchronization.vb
$ mono ChannelSynchronization.exe
working...done

In this Visual Basic .NET version:

  1. We use Task.Run to start our worker function asynchronously, similar to a goroutine.

  2. Instead of a channel, we use a ManualResetEventSlim for synchronization. This class provides a lightweight alternative to ManualResetEvent and is suitable for scenarios where you need to signal between a small number of threads.

  3. The Worker function signals completion by calling doneEvent.Set(), which is analogous to sending a value on a channel.

  4. In the Main function, we wait for the worker to complete by calling doneEvent.Wait(), which blocks until the event is signaled.

If you removed the doneEvent.Wait() line from this program, it would exit before the Worker even started, just like in the original example.

This approach demonstrates how to achieve similar synchronization behavior in Visual Basic .NET, even though the language doesn’t have built-in channels like some other languages do.