Writing multithreaded application in .NET and VB is pretty easy. This tutorial is for beginners who have not coded any multithreaded application in VB yet. Just follow these simple steps.
Define Namespace
In .NET, threading functionality is defined in System.Threading namespace. So you have to define System. Threading namespace before using any thread classes.
Imports
System.Threading Start a Thread
The Thread class of System.threading namespace represents a Thread object. By using this class object, you can create new threads, delete, pause, and resume threads. The Thread class creates a new thread and Thread.Start method starts the thread.
Private
thread As Thread = New Thread(New ThreadStart(WriteData))
thread.Start() Where WriteData is a function which will be executed by the thread. Protected
Sub WriteData()
Dim str As String
For i As Integer = 0 To 10000
str = "Secondary Thread" & i.ToString()
Console.WriteLine(listView1.ListItems.Count, str, 0, New String(){""})
Update()
Next i
End Sub Aborting a Thread
Thread class's Abort method is called to abort a thread. Make sure you call IsAlive before Abort.
If
thread.IsAlive Then
thread.Abort()
End If Note: When a call is made to the Abort method to destroy a thread, the common language runtime(CLR) throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before killing the thread. Since the thread can do an unbounded computation in the finally blocks, you must call the Join method to guarantee that the thread has died. Join is a blocking call that does not return until the thread actually stops executing.
Pausing a Thread
Thread.Sleep method can be used to pause a thread for a fixed period of time.
thread.Sleep()
Setting Thread Priority Thread class's ThreadPriority property is used to sets thread's priority. The thread priority can have Normal, AboveNormal, BelowNormal, Highest, and Lowest values. These are self-explanatory.
Private
thread.Priority = ThreadPriority.Highest Suspend a Thread
The Suspend method of the Thread class suspends a thread. The thread is suspended until Resume method is called.
If
thread.ThreadState = ThreadState.Running Then
thread.Suspend()
End If Resume a suspended Thread The Resume method is called to resume a suspended thread. If thread is not suspended, there will be no effect of Resume method.
If
thread.ThreadState = ThreadState.Suspended Then
thread.Resume()
End If