Our first example demonstrates the use of a WaitGroup to synchronize multiple threads. Here’s the full source code:
To run the program, save it as WaitGroupExample.vb and use the Visual Basic compiler:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Visual Basic .NET example, we use a CountdownEvent as an equivalent to Go’s WaitGroup. The CountdownEvent is initialized with the number of operations we want to wait for, and each operation signals the event when it’s done.
We use Task.Run to start each worker in a separate thread, which is similar to launching goroutines in Go. The Try/Finally block ensures that the CountdownEvent is signaled even if an exception occurs in the worker.
The wg.Wait() call blocks until all workers have finished, just like in the Go example.
Note that Visual Basic .NET and the .NET Framework provide more advanced concurrency patterns, such as the Task Parallel Library, which might be more suitable for complex scenarios.