By Steve Schofield
This code sample shows how to start multiple threads to enhance performance. I was looking for a way to increase performance of a console application that records information to a database. The code sample listed below has a couple of techniques. The first starts many threads and is used in the MyNewThread class.
The 'foo' class will spawn threads and wait for 30 seconds, then the thread is destroyed. This can help when you need to ensure results of connecting to the remote machine are returned. If there is an error, your code can evaluate and handle the error.
I recommend you check out Google for additional code samples or MSDN to provide help. This code is a 'hello world' app but can ensure your code will work before integrating into a larger application.
Imports System.Threading
Module Module1
Sub Main()
Dim x As Integer = 0
For x = 0 To 3
Dim newThread As New Thread(AddressOf Spawn)
newThread.Start()
Next
Console.WriteLine("Done")
End Sub
<MTAThread()> Public Sub Spawn()
'One Test to just start machine threads
'Test.foo()
'Start a new thread to do some work and waite for a response
MyNewThread.MyThread()
End Sub
End Module
Public Class Test
<MTAThread()> _
Public Shared Sub foo()
Dim newThread As New Thread(AddressOf Work.DoWork)
newThread.Start()
'Dim w As New Work()
w.Data = 42
newThread = New Thread(AddressOf w.DoMoreWork)
newThread.Start()
End Sub
End Class
Public Class Work
Public Shared Sub DoWork()
Console.WriteLine("Static thread procedure.")
End Sub
Public Data As Integer
Public Sub DoMoreWork()
Console.WriteLine("Instance thread procedure. Data={0}", Data)
End Sub
End Class
Public Class MyNewThread
Private Delegate Sub m_delMyDelegate()
<MTAThread()> Public Shared Sub MyThread()
Dim delThread1 As m_delMyDelegate = AddressOf GetComputerInfo
Dim ar1 As IAsyncResult
Dim a_WaitHandles(0) As System.Threading.WaitHandle
ar1 = delThread1.BeginInvoke(Nothing, Nothing)
a_WaitHandles(0) = ar1.AsyncWaitHandle
System.Threading.WaitHandle.WaitAll(a_WaitHandles, 30000, False)
If ar1.IsCompleted Then delThread1.EndInvoke(ar1)
End Sub
Private Shared Sub GetComputerInfo()
Threading.Thread.Sleep(29999)
End Sub
End Class
Steve Schofield is a Senior Internet Support Specialist with ORCS Web, Inc. - a company that provides managed complex hosting for clients who develop and deploy their applications on Microsoft Windows platforms.