Create a New Thread With or Without a Parameter in C#

A Thread runs a method on a new operating system thread, in parallel with the code that started it. You give the constructor the method to run, call Start, and optionally Join to wait for it to finish. The examples below show the two constructor forms, then the modern alternative you should normally reach for.

A thread without a parameter

var worker = new Thread(() =>
{
    Console.WriteLine($"Working on thread {Environment.CurrentManagedThreadId}");
});

worker.Start();
worker.Join(); // wait until it has finished

The lambda converts to the ThreadStart delegate, a method with no parameters and no return value. The original version of this post wrote new Thread(new ThreadStart(delegate() { ... })); the compiler has inferred the delegate type for you since C# 2, and lambdas replaced anonymous delegate syntax in C# 3.

A thread with a parameter

The second constructor takes a ParameterizedThreadStart, a method with one object? parameter. You pass the value to Start:

var worker = new Thread(PrintMessage);
worker.Start("Thread parameter");
worker.Join();

static void PrintMessage(object? state)
{
    var message = (string)state!;
    Console.WriteLine(message);
}

This works, but the parameter is typed as object, so you need a cast, value types are boxed, and passing the wrong type compiles fine and fails at run time. Passing two values means inventing a class or tuple to hold them.

Typed parameters with a lambda

A lambda that captures local variables avoids all of that. Use the parameterless form and call your method with whatever arguments it needs:

string fileName = "report.csv";
int maxRows = 500;

var worker = new Thread(() => ExportReport(fileName, maxRows));
worker.Start();
worker.Join();

static void ExportReport(string fileName, int maxRows)
{
    Console.WriteLine($"Exporting {maxRows} rows to {fileName}");
}

One trap: the lambda captures the variable, not its value at that moment. In a for loop, every thread shares the same loop variable and may see it after it has moved on. Copy it into a local inside the loop first (int copy = i;) and capture the copy. foreach does not have this problem since C# 5, because each iteration gets a fresh variable.

Foreground and background threads

A new Thread is a foreground thread by default, which means the process keeps running until it finishes, even after Main has returned. Set worker.IsBackground = true before Start if the thread should die with the application, which is usually what you want for helper threads in a desktop app.

An unhandled exception inside a thread’s method crashes the whole process. Nothing in the starting code can catch it, so wrap the body in try/catch if it can fail.

Use Task.Run instead

For almost all background work in current .NET, Task.Run is the better choice:

int count = await Task.Run(() => CountPrimesBelow(1_000_000));
Console.WriteLine($"{count} primes below one million");
// 78498 primes below one million

static int CountPrimesBelow(int limit)
{
    int count = 0;
    for (int n = 2; n < limit; n++)
    {
        bool isPrime = true;
        for (int d = 2; d * d <= n; d++)
        {
            if (n % d == 0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime) count++;
    }
    return count;
}

Compared with new Thread:

  • It returns a result. A Thread has no return value, so you would need a shared field and a Join.
  • Exceptions are captured and rethrown at the await, where an ordinary try/catch handles them.
  • It uses the thread pool. Every new thread costs a system call and reserves its own stack (1 MB by default on Windows); a pool thread is reused.
  • It composes with async/await, Task.WhenAll, cancellation tokens and timeouts.

And if the work is I/O, such as calling an API or querying a database, you do not need a thread at all. Await the async method directly (await httpClient.GetStringAsync(url)), and no thread sits blocked while you wait.

When Thread is still right

Create a Thread yourself when you need control the pool does not give you: a thread that runs for the lifetime of the app (a message loop or a queue consumer), a specific Priority, or a single-threaded apartment for COM or clipboard work via SetApartmentState(ApartmentState.STA) before Start. For a long-running loop you can also use Task.Factory.StartNew(work, TaskCreationOptions.LongRunning), which gives the task a dedicated thread while keeping the Task API.

Related examples

Leave a Comment