Languages
[Edit]
EN

C#/.NET - thread name

11 points
Created by:
Nabila-Burnett
385

In this article we would like to show how to set name for indicated thread in C# / .NET.

Quick solution:

Thread thread = new Thread(...);

thread.Name = "MyThreadName";  // <--------------- custom thread mane

 

Practical example

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 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).

 

Thread custom names during debugging process - C#.
Thread custom names during debugging process - C#.

 

 

References

  1. Thread Class - Microsoft Docs
  2. Thread.Name Property - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# - Thread Class

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join