C# Main Thread Example

Certainly! Here’s an example of a C# program that demonstrates the main thread:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // Print information about the main thread
        Thread mainThread = Thread.CurrentThread;
        Console.WriteLine($"Main Thread ID: {mainThread.ManagedThreadId}");
        Console.WriteLine($"Is Main Thread Background? {mainThread.IsBackground}");
        Console.WriteLine($"Is Main Thread a ThreadPool Thread? {mainThread.IsThreadPoolThread}");

        // Create a new thread and start it
        Thread newThread = new Thread(WorkerThread);
        newThread.Start();

        // Do some work in the main thread
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine($"Main Thread: Working on iteration {i}");
            Thread.Sleep(1000); // Simulate some work
        }

        // Wait for the new thread to finish
        newThread.Join();

        Console.WriteLine("Main Thread: Worker thread has finished. Exiting...");
    }

    static void WorkerThread()
    {
        Console.WriteLine("Worker Thread: Starting work...");

        // Simulate some work
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine($"Worker Thread: Working on iteration {i}");
            Thread.Sleep(2000); // Simulate some work
        }

        Console.WriteLine("Worker Thread: Work finished.");
    }
}

In this example, the program starts by printing information about the main thread, such as its ID, whether it’s a background thread, and whether it’s a thread from the thread pool.

Then, a new thread (newThread) is created and started using the Thread class. The new thread executes the WorkerThread method, which simulates some work by printing messages and pausing for a short time using Thread.Sleep.

Meanwhile, the main thread continues its work by printing messages and pausing for a short time. After the main thread finishes its work, it calls Join() on the newThread to wait for it to finish before exiting the program.

You can run this code in a C# environment to observe the behavior of the main thread and the worker thread.