csharp-threads

Threads in C#

  • 3 min

In C#, threads are a way to achieve concurrent and parallel programming. They allow us to divide a program’s execution into multiple tasks that can run simultaneously.

In many cases we need to perform tasks simultaneously, such as accessing a database while displaying an animation in the user interface. This is where threads allow dividing the work into concurrent tasks.

A thread is the smallest unit of processing in a program. Normally, a program has at least one thread, called the main thread, which is responsible for executing instructions in a sequential order.

Create and Run a Thread

In C#, you can create a thread by instantiating the Thread class and assigning it a method to execute. Then, we start the thread by calling the .Start() method.

using System;
using System.Threading;

public class Program
{
    public static void Main()
    {
        // Create a new thread
        Thread newThread = new Thread(BackgroundTask);
        newThread.Start(); // Start the thread

        // Task in the main thread
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Main thread running...");
            Thread.Sleep(1000);
        }
    }

    public static void BackgroundTask()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Secondary thread running...");
            Thread.Sleep(1000);
        }
    }
}
Copied!

The method that will run in the new thread must be of type void and must not have parameters (or parameters must be handled in an alternative way).

Useful Thread Methods and Properties

The Thread class provides several useful methods and properties:

Thread.Sleep(int milliseconds)

Suspends the execution of the current thread for the specified number of milliseconds. Useful for making pauses.

Thread.Join()

Makes the main thread wait for the secondary thread to complete its task before continuing. This is useful to ensure a thread has finished before proceeding with execution.

IsAlive

Property that indicates whether the thread is running.

Priority

Allows setting the thread’s priority (Low, Normal, High), which affects the relative execution order.

Thread newThread = new Thread(BackgroundTask);
newThread.Start();

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

Console.WriteLine("Secondary thread finished. Continuing in the main thread.");
Copied!