Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to display name of Current Thread
To display the name of the current thread in C#, use the Name property of the Thread.CurrentThread object. This property allows you to both set and retrieve the name of the currently executing thread.
Syntax
Following is the syntax to get the current thread −
Thread thread = Thread.CurrentThread;
Following is the syntax to set and get the thread name −
thread.Name = "ThreadName"; string currentName = thread.Name;
Using Thread.CurrentThread Property
The Thread.CurrentThread property returns a reference to the currently executing thread. You can then use the Name property to assign or retrieve the thread's name −
Example
using System;
using System.Threading;
namespace Demo {
class MyClass {
static void Main(string[] args) {
Thread thread = Thread.CurrentThread;
thread.Name = "My Thread";
Console.WriteLine("Thread Name = {0}", thread.Name);
}
}
}
The output of the above code is −
Thread Name = My Thread
Displaying Thread Information
You can display additional information about the current thread along with its name −
Example
using System;
using System.Threading;
class ThreadInfo {
static void Main() {
Thread currentThread = Thread.CurrentThread;
currentThread.Name = "MainThread";
Console.WriteLine("Thread Name: " + currentThread.Name);
Console.WriteLine("Thread ID: " + currentThread.ManagedThreadId);
Console.WriteLine("Is Background: " + currentThread.IsBackground);
Console.WriteLine("Thread State: " + currentThread.ThreadState);
}
}
The output of the above code is −
Thread Name: MainThread Thread ID: 1 Is Background: False Thread State: Running
Handling Unnamed Threads
If no name is assigned to a thread, the Name property returns null. You can check for this condition −
Example
using System;
using System.Threading;
class Program {
static void Main() {
Thread thread = Thread.CurrentThread;
if (thread.Name == null) {
Console.WriteLine("Thread has no name assigned");
thread.Name = "DefaultThread";
}
Console.WriteLine("Current thread name: " + thread.Name);
}
}
The output of the above code is −
Thread has no name assigned Current thread name: DefaultThread
Conclusion
The Thread.CurrentThread.Name property in C# provides an easy way to identify and manage threads by assigning meaningful names. This is particularly useful for debugging and monitoring multi-threaded applications where you need to track specific threads.
