Creating Threads

Create and run threads in a .NET application.

Introduction

It’s possible to create and launch multiple threads within a single .NET application. We can use one of the Thread class constructors to create a thread. We must provide an action that executes on our thread. An action, in this context, is essentially a method that runs on the thread we create.

The Thread class supports two types of methods:

  • Parameterless methods that don’t return any value (void).
  • Parameterized methods that don’t return any value (void).

In this lesson, we’ll cover the execution of parameterless methods.

The ThreadStart delegate

The Thread class supports parameterless methods that have the same signature and return type as the ThreadStart delegate. The Thread has a constructor that accepts a ThreadStart delegate object:

public Thread(ThreadStart start)
{
}

The ThreadStart object is a delegate with the following definition:

public delegate void ThreadStart();

There are three approaches we could take here:

  1. We could instantiate a ThreadStart delegate object and pass it to the constructor.
  2. We could pass a suitable method directly to the constructor without explicitly creating a delegate object.
  3. We could pass a suitable anonymous method.

A method we want to pass is suitable when it conforms to the ThreadStart delegate.

The following code shows all three approaches:

Get hands-on with 1200+ tech skills courses.