Search⌘ K
AI Features

Parameterized Methods

Explore how to run threads with parameters in C# by using the ParameterizedThreadStart delegate. Understand its limitations with single object parameters and how to pass multiple values using arrays or custom types. Learn modern approaches like lambda expressions to maintain type safety and improve code clarity in asynchronous execution.

Running a parameterless method on a thread is achieved by passing an instance of the ThreadStart delegate to a Thread constructor. However, we often need to pass some parameters to the thread for it to process. The ParameterizedThreadStart delegate is used for this purpose.

The ParameterizedThreadStart delegate

Running a parameterless method on a thread is achieved by passing an instance of the ThreadStart delegate to a Thread constructor. However, threads often require input data. The ParameterizedThreadStart delegate is designed for this purpose:

public Thread(ParameterizedThreadStart start)
{
}

The ParameterizedThreadStart delegate has the following definition:

public delegate void ParameterizedThreadStart(object? obj);

Usage is similar to creating a thread with ThreadStart. Let’s look at the syntax using modern top-level ...

C# 14.0
using System.Threading;
// 1. Create a ParameterizedThreadStart delegate object explicitly
var parameterizedThreadStart = new ParameterizedThreadStart(PrintMessage);
var thread1 = new Thread(parameterizedThreadStart);
// 2. Pass a method name directly (Method Group)
var thread2 = new Thread(PrintMessage);
// 3. Pass an anonymous method (Lambda)
var thread3 = new Thread((message) =>
{
Console.WriteLine(message);
});
void PrintMessage(object? message)
{
Console.WriteLine("Hello World!");
}
...