
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
C# Program to Kill a Thread
Create a thread first and start it −
// new thread Thread thread = new Thread(c.display); thread.Start();
Now display the thread and set a stop function to stop the working of the thread −
public void display() { while (!flag) { Console.WriteLine("It's Working"); Thread.Sleep(2000); } } public void Stop() { flag = true; } }
Example
The following is the complete code to learn how to kill a thread in C#.
using System; using System.Threading.Tasks; using System.Threading; class Demo { static void Main(string[] args){ MyClass c = new MyClass(); // new thread Thread thread = new Thread(c.display); thread.Start(); Console.WriteLine("Press any key to exit!"); Console.ReadKey(); c.Stop(); thread.Join(); } } public class MyClass { private bool flag = false; public void display() { while (!flag) { Console.WriteLine("It's Working"); Thread.Sleep(2000); } . } . public void Stop() { flag = true; } }
Output
It's Working Press any key to exit!
- Related Articles
- C# Program to Pause a Thread
- C# Program to create a Simple Thread
- C# Program to Create a Thread Pool
- C# Program to pass Parameter to a Thread
- C# Program to display priority of Thread
- C# Program to Check status of Current Thread
- C# Program to display name of Current Thread
- C# Program to implement Sleep Method Of Thread
- How to Kill a Process by Name in Linux?
- How to Kill a Detached screen Session on Linux
- C++ program to find minimum number of locations to place bombs to kill all monsters
- How to get the thread ID from a thread in C#?
- Kill a process running on a specific port?
- How to check whether a thread is a background thread or not in C#
- Windows thread API in the C program

Advertisements