Working with Threads in C#

Tutorial 2 of 5

Working with Threads in C

1. Introduction

In this tutorial, we will explore how to work with threads in C#. Threads provide a way to achieve multitasking in programs, allowing multiple execution paths to run concurrently. We'll learn how to create, start, pause, and terminate threads, and how to handle exceptions within threads.

By the end of this tutorial, you will have a clear understanding of:

  • How to create and start a thread in C#
  • How to pause and resume a thread
  • How to terminate a thread
  • How to handle exceptions in threads

Prerequisites: Basic knowledge of C# programming and understanding of object-oriented programming concepts.

2. Step-by-Step Guide

What is a Thread?

A thread is the smallest unit of execution within a process. In C#, the System.Threading namespace provides the Thread class to work with threads.

Creating and Starting a Thread

To create a thread in C#, you need to create an instance of the Thread class and pass the method you want to run on the thread as a parameter to the Thread constructor.

Thread myThread = new Thread(new ThreadStart(MyThreadMethod));

Then, call Start() method to start the thread.

myThread.Start();

Pausing and Resuming a Thread

To pause a thread, you can use the Thread.Sleep() method which blocks the current thread for a specified time.

Thread.Sleep(5000); // Pauses the current thread for 5 seconds

Terminating a Thread

To terminate a thread, the Abort() method is used. It raises a ThreadAbortException that can be caught and handled.

myThread.Abort();

Handling Exceptions in Threads

Uncaught exceptions in a thread, other than the main thread, are allowed to proceed and terminate that thread.

try 
{
    myThread.Start();
}
catch (Exception ex) 
{
    Console.WriteLine(ex.Message);
}

3. Code Examples

Example 1: Creating and Starting a Thread

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // Create a new thread
        Thread myThread = new Thread(new ThreadStart(CountToTen));

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

    static void CountToTen()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

This program creates a new thread and starts it. The CountToTen method will be executed on the new thread.

Expected output:

1
2
3
4
5
6
7
8
9
10

Example 2: Pausing and Resuming a Thread

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // Create a new thread
        Thread myThread = new Thread(new ThreadStart(CountToTen));

        // Start the thread
        myThread.Start();

        // Pause the main thread for 5 seconds
        Thread.Sleep(5000);

        Console.WriteLine("Main thread resumes.");
    }

    static void CountToTen()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
            Thread.Sleep(1000);  // Pause the current thread for 1 second
        }
    }
}

This program pauses the main thread for 5 seconds before printing "Main thread resumes.", and each number in CountToTen is printed every second.

Example 3: Terminating a Thread

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // Create a new thread
        Thread myThread = new Thread(new ThreadStart(CountForever));

        // Start the thread
        myThread.Start();

        // Wait for 5 seconds then terminate the thread
        Thread.Sleep(5000);
        myThread.Abort();

        Console.WriteLine("Thread terminated.");
    }

    static void CountForever()
    {
        int i = 1;
        while (true)
        {
            Console.WriteLine(i++);
        }
    }
}

This program prints numbers continuously until the thread is terminated after 5 seconds.

4. Summary

In this tutorial, we have learned about creating, starting, pausing, and terminating threads in C#. We've also learned how to handle exceptions within threads.

Next steps: To further your knowledge, learn about advanced threading topics such as ThreadPool, Mutex, Semaphore, Monitor, and Thread Synchronization.

Additional resources:
- Microsoft Docs - Threading in C#
- C# Station - Threading

5. Practice Exercises

Exercise 1: Create a program that prints "Hello, World!" in a separate thread.

Exercise 2: Create a program that counts to 100 in a separate thread, but the main thread should wait until the counting is finished before terminating.

Exercise 3: Create a program that has two threads, one that counts up to 50 and another that counts down from 50 to 1. Handle any potential exceptions.

Remember to practice regularly to strengthen your understanding and skill. Happy coding!