Parallel Programming

Measure speedup (Amdahl's law). Avoid shared mutable state. Partition the work. Watch for false sharing and oversubscription.

TPL Dataflow (System.Threading.Tasks.Dataflow) for pipeline graphs (TransformBlock, ActionBlock, BufferBlock).

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

' Data parallelism
Parallel.ForEach(imagePaths, New ParallelOptions With {.MaxDegreeOfParallelism = Environment.ProcessorCount},
                 Sub(path) CreateThumbnail(path))

Dim totals As New Concurrent.ConcurrentDictionary(Of String, Decimal)
Parallel.ForEach(orders, Sub(o) totals.AddOrUpdate(o.Region, o.Total, Function(k, v) v + o.Total))

' Async parallelism with throttling (.NET 6+)
Await Parallel.ForEachAsync(urls, New ParallelOptions With {.MaxDegreeOfParallelism = 8},
    Async Function(url, ct)
        Dim html = Await _http.GetStringAsync(url, ct)
        Await SaveAsync(url, html, ct)
    End Function)

' PLINQ
Dim primeCount = Enumerable.Range(2, 5_000_000).AsParallel().Count(Function(n) IsPrime(n))

' Producer/consumer with Channels
Dim channel = Channel.CreateBounded(Of String)(New BoundedChannelOptions(100) With {.FullMode = BoundedChannelFullMode.Wait})
Dim producer = Task.Run(Async Function()
                            For Each line In IO.File.ReadLines("big.log")
                                Await channel.Writer.WriteAsync(line)
                            Next
                            c
…