VB.Net - SPLessons

VB.Net Multi threading

Home > Lesson > Chapter 27
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

VB.Net Multi threading

VB.Net Multi threading

shape Description

A thread can be defined as a program or a task and it consists of the program counter , a unique id, set of registers, a stack. Multi threading can be defined practically as to run the process only executing task is completed it mean that automatically next process supposed to wait till the first one gets executed . Following example describes the concept of multi threading in VB.Net by creating form. 

shape Example

In this example take two labels and three buttons as follows. Where created count time first two buttons as mentioned in the code, when we click on Button1 count starts from 0 to 100 and when click on Button2 count starts from 101 to 200 and when click on Button3 count will be stopped, when click on Button1 count begins on label1 and click on Button2 count begins on label2.According to this requirement code has been written as follows. [vbnet]Imports System.Threading Imports System.ComponentModel Class Form1 Public thread1 As Thread = Nothing Public thread2 As Thread = Nothing Public Delegate Sub delegate1(ByVal [num1] As Integer) Public Delegate Sub delegate2(ByVal [num2] As Integer) Public Sub Count1() Dim d As New delegate1(AddressOf SetLabel1) For i = 0 To 100 If Me.Label1.InvokeRequired Then Me.Invoke(d, New Object() {i}) Else Me.Label1.Text = i.ToString End If Me.Label1.Text = i.ToString Next End Sub Public Sub SetLabel1(ByVal [mynum] As Integer) Me.Label1.Text = mynum.ToString Thread.Sleep(100) End Sub Public Sub Count2() Dim d As New delegate2(AddressOf SetLabel2) For i = 101 To 200 If Me.Label2.InvokeRequired Then Me.Invoke(d, New Object() {i}) Else Me.Label2.Text = i.ToString End If Thread.Sleep(100) Next End Sub Public Sub SetLabel2(ByVal [mynum] As Integer) Me.Label2.Text=mynum.ToString End Sub Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click thread1 = New Thread(AddressOf Count1) thread1.Start() End Sub Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click thread2 = New Thread(AddressOf Count2) thread2.Start() End Sub Private Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click thread1.Abort() thread2.Abort() End Sub End Class [/vbnet] Output: Result will be as follows , when click on Button 1 and Button 2 count will be started and Button3 has designed to stop the count.

Summary

shape Points

  • Multi threading will use thread.sleep() method.
  • The thread.start() is utilized to start the process.
  • The good feature of multi threading is event handling.