C# - How to Assign the Name to the Thread?

Here, we are going to learn how to assign the name to the thread in C#? By Nidhi Last updated : March 29, 2023

To set/assign the thread's name, we use Thread.CurrentThread.Name propery. The Name property is used to set and get the name of a thread.

C# program to assign the name to the thread

/*
 * Program to assign the name to the thread in C#.
 */

using System;
using System.Threading;

class ThreadEx {
  static void Main() {
    if (Thread.CurrentThread.Name == null) {
      Thread.CurrentThread.Name = "MyMainThread";
      Console.WriteLine("Name of the thread assigned successfully");
    } else {
      Console.WriteLine("Name of thread already assigned");
    }
  }
}

Output

Name of the thread assigned successfully
Press any key to continue . . .

Explanation

In the above program, we created a class ThreadEx that contains the Main() method. The Main() method contains the below code.

if (Thread.CurrentThread.Name == null)
{
    Thread.CurrentThread.Name = "MyMainThread";
    Console.WriteLine("Name of the thread assigned successfully");
}
else
{
    Console.WriteLine("Name of thread already assigned");
}

In the above code we checked if Name property contains "null" value then we assigned the MyMainThread name to the current thread otherwise we print "Name of thread already assigned" on the console screen.

C# Thread Programs »


Comments and Discussions!

Load comments ↻






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