' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.Threading

Namespace PoolOld
    Public Class Program
        Public Class Counter
            Public Property N() As Integer
        End Class
        Public Class Data
            Public Property S() As String
        End Class
        Public Class Processor
            Private d As Data
            Public Sub New(d As Data)
                Me.d = d
            End Sub
            Public Sub Run(c As Object)
                ' simulate a lot of work that takes 0.1 second
                Dim s As String = d.S
                Thread.Sleep(100)
                d.S = s & "X"
                ' count down
                SyncLock c
                    DirectCast(c, Counter).N -= 1
                End SyncLock
            End Sub
        End Class
        Public Shared Sub Test(njobs As Integer, nthreads As Integer)
            ' setup data
            Dim d As Data() = New Data(njobs - 1) {}
            For i As Integer = 0 To njobs - 1
                d(i) = New Data() With { .S = "X" }
            Next
            ' process
            Dim dt1 As DateTime = DateTime.Now
            ThreadPool.SetMinThreads(nthreads, nthreads)
            ThreadPool.SetMaxThreads(nthreads, nthreads)
            ' submit jobs
            Dim c As New Counter() With { .N = njobs }
            For i As Integer = 0 To njobs - 1
                ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf (New Processor(d(i))).Run), c)
            Next
            ' wait for jobs to complete
            While True
                SyncLock c
                    If c.N <= 0 Then
                        Exit While
                    End If
                End SyncLock
                Thread.Sleep(25)
            End While
            Dim dt2 As DateTime = DateTime.Now
            Console.WriteLine("{0} jobs executing in {1} threads : {2:F1} seconds", njobs, nthreads, (dt2 - dt1).TotalSeconds)
            ' check data
            For i As Integer = 0 To njobs - 1
                If d(i).S <> "XX" Then
                    Console.WriteLine("Ooops")
                End If
            Next
        End Sub
        Public Shared Sub Main(args As String())
            Test(256, 1)
            Test(256, 2)
            Test(256, 4)
            Test(256, 8)
            Test(256, 16)
            Test(256, 32)
            Test(256, 64)
            Console.ReadKey()
        End Sub
    End Class
End Namespace
