Multi-threading with C# examples

What is thread?

Program blocks are made of bunch of statements. These statements inside the program blocks are executed generally one after the other. With threads it is possible to execute 2 or more program blocks parallelly.

As a programmer, it's important to grasp the benefits threads offer. Delving into their functionality and implementation details can be a topic for another time.

Need for threads

Consider a web server, now to serve a web request there would be a block of code. Executing this block of code will serve on request. In a web server, we cannot serve one request after the other especially in scenarios where time taken to serve a web request is significant. Threads come in handy to solve this problem. Most web servers serve different web request using different threads.

Demonstration

Sample code

In the below code

  • WriteHash method writes "#### <some number>" to the console every 200 ms

  • WriteStar method writes "* <some number>" to the console every 250 ms 10 times

  • The main program calls the WriteStar method

  • The main program also creates a background thread and that executes WriteHash method

var thread1 = new Thread(() => WriteHash());
thread1.IsBackground = true;
thread1.Start();
WriteStar();

static void WriteHash()
{
    int i = 0;
    while (true)
    {
        i++;
        Console.WriteLine($"#### {i}");
        Thread.Sleep(200);
    }
}

static void WriteStar()
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine($"* {i}");
        Thread.Sleep(250);
    }
}

Program Output

Further reading

  • What is background thread?

  • What is the difference between threads and tasks?

Code Reference

This repo contains all the code that was used for this demonstration.