EN
C#/.NET - thread name
11 points
In this article we would like to show how to set name for indicated thread in C# / .NET.
Quick solution:
xxxxxxxxxx
1
Thread thread = new Thread(...);
2
3
thread.Name = "MyThreadName"; // <--------------- custom thread mane
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
class Program
7
{
8
static void Main(string[] args)
9
{
10
Thread.CurrentThread.Name = "MyMainThread";
11
12
Thread thread = new Thread(() =>
13
{
14
Thread.Sleep(5000);
15
Console.WriteLine(Thread.CurrentThread.Name + " is stopping");
16
});
17
18
thread.Name = "MyFirstThread";
19
thread.Start();
20
21
Thread.Sleep(5000);
22
Console.WriteLine(Thread.CurrentThread.Name + " is stopping");
23
}
24
}
25
}
Where:
Thread.CurrentThread
property - keeps reference to currently executed thread objectThread.Name
property - gets and sets thread name
Output:
xxxxxxxxxx
1
MyFirstThread is stopping
2
MyMainThread is stopping
Note:
Thread.Name
helps to identify threads more precisely. In Visual Studio the threads window shows all threads with their names during debugging proces. To display the window use menu: Debug->Window->Threads (this menu is available only during debugging process).