Naming a thread and fetching name of current thread in C#
Last Updated :
24 Jan, 2019
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:
using System;
using System.Threading;
class Geek {
public void value()
{
Thread thr = Thread.CurrentThread;
Console.WriteLine( "The name of the current " +
"thread is: " + thr.Name);
}
}
public class GFG {
static public void Main()
{
Geek obj = new Geek();
Thread thr1 = new Thread(obj.value);
Thread thr2 = new Thread(obj.value);
Thread thr3 = new Thread(obj.value);
Thread thr4 = new Thread(obj.value);
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:
using System;
using System.Threading;
class Name {
static void Main()
{
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:
Share your thoughts in the comments
Please Login to comment...