Languages
[Edit]
EN

C#/.NET - thread name

8 points
Created by:
Marcin
2462

To name thread in C#/.NET Thread.Name property can be used.

using System;
using System.Threading;

namespace Test
{
	class Program
	{
		static void Main(string[] args)
		{
			Thread.CurrentThread.Name = "MyMainThread";

			Thread thread = new Thread(() =>
			{
				Thread.Sleep(5000);
				Console.WriteLine(Thread.CurrentThread.Name + " is stopping");
			});

			thread.Name = "MyFirstThread";
			thread.Start();

			Thread.Sleep(5000);
			Console.WriteLine(Thread.CurrentThread.Name + " is stopping");
		}
	}
}

Where:

  • Thread.CurrentThread property - keeps reference to currently executed thread object
  • Thread.Name property - gets and sets thread name

Output:

MyFirstThread is stopping
MyMainThread is stopping
 Note:
Thread.Name helps to identify more precisely threads. 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).

Thread names during debugging process

References

  1. Thread Class - Microsoft Docs
  2. Thread.Name Property - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.