Naming a thread and fetching name of current thread in C#

Naming a thread and fetching name of current thread

In C#, you can set and retrieve the name of a thread using the Thread class which is part of the System.Threading namespace. Below is a brief tutorial demonstrating how to name a thread and fetch its name:

1. Setting up the environment:

First, make sure to include the necessary using directive:

using System; using System.Threading; 

2. Naming a Thread:

You can name a thread using the Name property of the Thread class.

Thread.CurrentThread.Name = "MainThread"; 

3. Fetching the Name of the Current Thread:

You can get the name of the current thread using the same Name property.

string threadName = Thread.CurrentThread.Name; Console.WriteLine($"Current thread name: {threadName}"); 

4. Full Example:

Below is a full example demonstrating the concepts:

using System; using System.Threading; namespace ThreadNameTutorial { class Program { static void Main() { // Naming the main thread Thread.CurrentThread.Name = "MainThread"; // Fetching and displaying the name of the current thread Console.WriteLine($"Main method runs on thread: {Thread.CurrentThread.Name}"); // Creating a new thread and naming it Thread newThread = new Thread(NewThreadMethod); newThread.Name = "SecondaryThread"; newThread.Start(); } static void NewThreadMethod() { Console.WriteLine($"This is {Thread.CurrentThread.Name}"); } } } 

When you run the program, you should see output similar to:

Main method runs on thread: MainThread This is SecondaryThread 

Remember, setting a thread's name can only be done once; attempting to rename a thread will result in an InvalidOperationException.


More Tags

duplicates gpu office365api numericupdown html-datalist skew crystal-reports-formulas constraint-validation-api xcuitest spring-mongo

More Programming Guides

Other Guides

More Programming Examples