0
0
CsharpHow-ToBeginner · 4 min read

How to Create Thread in C#: Simple Guide with Examples

In C#, you create a thread by using the Thread class from System.Threading. You define a method for the thread to run, then create a Thread object with that method and start it using Start().
📐

Syntax

To create a thread in C#, you use the Thread class. You pass a method (called a thread start) to the thread constructor. Then you call Start() to run the thread.

  • ThreadStart: Delegate that points to the method the thread will execute.
  • Thread: Class representing the thread.
  • Start(): Method to begin thread execution.
csharp
using System.Threading;

class Program
{
    // Define a method to run on the thread
    static void MyThreadMethod()
    {
        // Code to run in the thread
    }

    static void Main()
    {
        // Create a thread object
        Thread myThread = new Thread(new ThreadStart(MyThreadMethod));

        // Start the thread
        myThread.Start();
    }
}
💻

Example

This example shows how to create and start a thread that prints numbers from 1 to 5 with a delay. It demonstrates basic thread creation and running in C#.

csharp
using System;
using System.Threading;

class Program
{
    static void PrintNumbers()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Number: {i}");
            Thread.Sleep(500); // Pause for 500 milliseconds
        }
    }

    static void Main()
    {
        Thread thread = new Thread(PrintNumbers);
        thread.Start();

        // Main thread continues to run
        Console.WriteLine("Main thread is running...");
        thread.Join(); // Wait for the thread to finish
        Console.WriteLine("Thread finished.");
    }
}
Output
Main thread is running... Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Thread finished.
⚠️

Common Pitfalls

Some common mistakes when creating threads in C# include:

  • Not starting the thread with Start(), so the thread never runs.
  • Accessing shared data without synchronization, causing race conditions.
  • Forgetting to wait for the thread to finish if needed, which can cause the program to exit early.
  • Using anonymous methods or lambdas incorrectly, leading to unexpected behavior.
csharp
using System;
using System.Threading;

class Program
{
    static int counter = 0;

    static void Increment()
    {
        for (int i = 0; i < 1000; i++)
        {
            counter++; // Unsafe access without lock
        }
    }

    static void Main()
    {
        Thread t1 = new Thread(Increment);
        Thread t2 = new Thread(Increment);

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine($"Counter value: {counter}");
    }
}
Output
Counter value: (may vary, often less than 2000 due to race conditions)
📊

Quick Reference

Here is a quick summary of key points for creating threads in C#:

  • Thread creation: Use new Thread(MethodName).
  • Start thread: Call Start() on the thread object.
  • Wait for thread: Use Join() to wait for completion.
  • Thread safety: Protect shared data with locks or synchronization.

Key Takeaways

Create a thread by passing a method to the Thread constructor and call Start() to run it.
Always start your thread with Start(), or it will not execute.
Use Join() if you need to wait for a thread to finish before continuing.
Protect shared data accessed by multiple threads to avoid race conditions.
Thread creation is simple but managing thread safety is crucial for correct programs.