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

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 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.