What is the use of Thread.Name?

How do you identify which thread executes the code and which thread causing an issue in the code. The Thread.Name property helps here. Let us see a simple example.




namespace My_Samples
{
using System.Threading;
using System;

class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(MyMethod);
t1.Name = "Thread 1";
t1.Start();

Thread t2 = new Thread(MyMethod);
t2.Name = "Thread 2";
t2.Start();

Console.WriteLine("Main Method...");
Console.ReadLine();
}

static void MyMethod()
{
Console.WriteLine(Thread.CurrentThread.Name);
}
}
}


The output will be something similar as below.

Thread 1
Main Method
Thread 2

No comments:

Post a Comment