C# Threading Example: Naming Thread

Certainly! Here’s an example of how you can name a thread in C#:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // Create a new thread and assign a name to it
        Thread thread = new Thread(DoWork);
        thread.Name = "WorkerThread";

        // Start the thread
        thread.Start();

        // Do some other work in the main thread
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Main thread doing some work.");
            Thread.Sleep(1000);
        }
    }

    static void DoWork()
    {
        // Perform some work in the thread
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Worker thread doing some work.");
            Thread.Sleep(1000);
        }
    }
}

In this example, a new thread is created using the Thread class constructor. The name of the thread is set using the Name property. The thread is then started with the Start method.

The main thread continues to execute its own work while the worker thread performs its own work. The DoWork method is executed in the worker thread, where it prints a message and sleeps for one second repeatedly.

The main thread also prints a message and sleeps for one second in its own loop. This allows you to see the interleaved output from both threads.

By naming the thread, you can easily identify it in the output, which is particularly useful when dealing with multiple threads in a complex application.