VB.Net program to kill a thread

Here, we are going to learn how to kill a thread in VB.Net?
Submitted by Nidhi, on January 04, 2021 [Last updated : March 08, 2023]

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")
            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)

        Console.WriteLine("Hit Any Key to finish execution!!!")

    End Sub
End Module


Hit Any Key to finish execution!!!
->Thread is running
->Thread is running
->Thread is running
->Thread is running
Press any key to continue . . .


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 »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.