C# Create Thread

In C#, threads can be created and started by using the Thread class from the System.Threading namespace. You can create a new thread, define the method to execute on that thread, and then start it.

Example: Creating and Starting a Thread


using System;
using System.Threading;

class MyProgram
{
    // This method will be executed by the new thread
    static void PrintTwoTable()
    {
        for (int i = 2; i <= 20; i+=2)
        {
            Console.WriteLine($"Number: {i}");
            Thread.Sleep(500); // Sleep for 500 milliseconds to simulate work
        }
    }

    static void Main()
    {
        // Create a new thread and specify the method to run
        Thread thread = new Thread(PrintTwoTable);

        // Start the thread
        thread.Start();

        // Main thread can continue to execute other code
        Console.WriteLine("Main thread continues executing...");

        thread.Join(); // This blocks the main thread until the created thread finishes

        Console.WriteLine("Main thread has finished execution.");
    }
}

Output:

Main thread continues executing...
Number: 2
Number: 4
Number: 6
Number: 8
Number: 10
Number: 12
Number: 14
Number: 16
Number: 18
Number: 20
Main thread has finished execution.

Explanation:

1. Creating a Thread: A new Thread object is created, passing the method (PrintTwoTable) that should be executed on that thread.


Thread thread = new Thread(PrintTwoTable);

2. Starting the Thread: The Start() method is called on the Thread object, which initiates the execution of the specified method (PrintTwoTable) on a new thread.


thread.Start();

3. Main Thread Execution: While the new thread is running, the main thread can continue to execute other instructions, such as printing messages to the console.


Console.WriteLine("Main thread continues executing...");

4. Waiting for the Thread to Finish: The Join() method is called to block the main thread until the new thread finishes executing. Without this, the main thread might finish its execution (and potentially terminate the application) before the new thread completes.


thread.Join();