Tutorialspoint.dev

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

A thread is a light-weight process within a process. In C#, a user is allowed to assign a name to the thread and also find the name of the current working thread by using the Thread.Name property of the Thread class.

Syntax :

public string Name { get; set; }

Here, the string contains the name of the thread or null if no name was assigned or set.

Important Points:

  • The by default value of the Name property is null.
  • The string given to the name property can include any Unicode Character.
  • The name property of Thread class is write-once.
  • If a set operation was requested, but the Name property has already set, then it will give InvalidOperationException.

Example 1:



// C# program to illustrate the 
// concept of assigning names 
// to the thread and fetching
// name of the current working thread
using System;
using System.Threading;
  
class Geek {
  
    // Method of Geek class
    public void value()
    {
        // Fetching the name of 
        // the current thread
        // Using Name property
        Thread thr = Thread.CurrentThread;
        Console.WriteLine("The name of the current "+
                           "thread is: " + thr.Name);
    }
}
  
// Driver class
public class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Creating object of Geek class
        Geek obj = new Geek();
  
        // Creating and initializing threads
        Thread thr1 = new Thread(obj.value);
        Thread thr2 = new Thread(obj.value);
        Thread thr3 = new Thread(obj.value);
        Thread thr4 = new Thread(obj.value);
  
        // Assigning the names of the threads
        // Using Name property
        thr1.Name = "Geeks1";
        thr2.Name = "Geeks2";
        thr3.Name = "Geeks3";
        thr4.Name = "Geeks4";
  
        thr1.Start();
        thr2.Start();
        thr3.Start();
        thr4.Start();
    }
}

Output:

The name of the current thread is: Geeks2
The name of the current thread is: Geeks3
The name of the current thread is: Geeks4
The name of the current thread is: Geeks1

Example 2:

// C# program to illustrate the 
// concept of giving a name to thread
using System;
using System.Threading;
  
class Name {
    static void Main()
    {
  
        // Check whether the thread
        // has already been named
        // to avoid InvalidOperationException
        if (Thread.CurrentThread.Name == null) {
  
            Thread.CurrentThread.Name = "MyThread";
            Console.WriteLine("The name of the thread is MyThread");
        }
        else {
            Console.WriteLine("Unable to name the given thread");
        }
    }
}

Output:

The name of the thread is MyThread

Reference:



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter