Multithreading in VB.NET
In this article you can see how thread works one by one in an application of VB.NET
Multithreading is the ability to do several things at a time. A lengthy task is divided into short segments , this segments called thread. In multithreading the times gets divided by the computer into parts and when a new thread starts, that thread gets a portion of divided time.
Following code represent how to deposit, check and update the customer account.
Imports System
Imports System.Threading
Public Module ThreadSample
Public Balance As Integer = 10
Sub Main()
Dim account As Account = New Account()
Dim depositeBalance1 As DepositeBalance = New DepositeBalance(account, 10, "Customer 1")
Dim depositeBalance2 As DepositeBalance = New DepositeBalance(account, 10, "Customer 2")
Dim t1 As Thread = New Thread(AddressOf depositeBalance1.DepositeAmount)
Dim t2 As Thread = New Thread(AddressOf depositeBalance2.DepositeAmount)
t1.Start()
t2.Start()
Try
t1.Join()
t2.Join()
Catch e As Exception
Console.Write(e.ToString())
Finally
End Try
Console.ReadLine()
End Sub
Public Class Account
Private balanceAmount As Integer
Public Sub Deposite(ByVal amount As Integer, ByVal message As String)
Console.WriteLine(message & "Depositing Amount " & amount)
Console.WriteLine(message & " Checking Previous Balance")
Monitor.Enter(Me)
balanceAmount = getBalance()
Console.WriteLine(message & "Previous Balance in Account " & balanceAmount)
balanceAmount += amount
Console.WriteLine(message & " Updating Balance in Account ")
setBalance(balanceAmount)
Monitor.Exit(Me)
Console.WriteLine(message & " Update Balance " & Balance)
End Sub
Private Function getBalance() As Integer
Try
Thread.Sleep(1000)
Catch e As Exception
Console.Write(e.ToString())
Finally
End Try
Return Balance
End Function
Private Sub setBalance(ByVal amount As Integer)
Try
Thread.Sleep(1000)
Catch e As Exception
Console.Write(e.ToString())
Finally
End Try
Balance = amount
End Sub
End Class
Public Class DepositeBalance
Private account As Account
Private amount As Integer
Private message As String
Public Sub New(ByRef account As Account, ByVal amount As Integer, ByVal message As String)
MyBase.New()
Me.account = account
Me.amount = amount
Me.message = message
End Sub
Public Sub DepositeAmount()
account.Deposite(amount, message)
End Sub
End Class
End Module
The output shows on windows console application like in below figure.
CONCLUSON: You just copy this code and pest in vb.net and debug the application you will see how multithreading works.