Home »
VB.Net »
VB.Net Programs
VB.Net program to kill a thread
By Nidhi Last Updated : November 15, 2024
How to kill a thread in VB.Net?
To kill a thread in VB.Net, here we implemented the program to stop running thread when a key is pressed by the user, if the user will not press the key then the thread will run indefinitely.
Program/Source Code:
The source code to kill a thread is given below. The given program is compiled and executed successfully.
VB.Net code to demonstrate the example of kill a thread
'Vb.Net program to kill a thread.
Imports System.Threading
Module Module1
Class MyThread
Private thread_flag As Boolean = False
Public Sub ThreadFun()
While (thread_flag = False)
Console.WriteLine("->Thread is running")
Thread.Sleep(500)
End While
End Sub
Public Sub StopThread()
thread_flag = True
End Sub
End Class
Sub Main()
Dim MT As New MyThread()
Dim T1 As New Thread(AddressOf MT.ThreadFun)
T1.Start()
Console.WriteLine("Hit Any Key to finish execution!!!")
Console.ReadKey()
MT.StopThread()
T1.Join()
End Sub
End Module
Output
Hit Any Key to finish execution!!!
->Thread is running
->Thread is running
->Thread is running
->Thread is running
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains a class MyThread and a function Main(). The Mythread contains a method ThreadFun() and a boolean data member thread_flag to check the condition for the thread running status. We set thread_flag to "true" when the Stop method is called, then condition of while loop gets false and ThreadFun() method will be finished.
The Main() function is the entry point for the program, here we created a thread and wait for the key to press. When we HIT any key from the keyboard, after that StopThread() method will be call and stop the thread. If we will not press any key then the thread will execute indefinitely.
VB.Net Threading Programs »