How to pass parameters to threads in C#?

In C#, you can pass parameters to a thread using the ParameterizedThreadStart delegate in the Thread class. Below is an example code:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // 创建一个线程,并传递参数给线程
        Thread thread = new Thread(new ParameterizedThreadStart(WorkThread));
        thread.Start("Hello, World!");

        Console.WriteLine("主线程");

        Console.ReadLine();
    }

    static void WorkThread(object data)
    {
        string message = (string)data;
        Console.WriteLine("工作线程收到参数:{0}", message);
    }
}

In the above code, we created a new thread and passed parameters to it through the ParameterizedThreadStart delegate. Within the worker thread, we converted the received parameters to the required type and performed the necessary operations.

Please note that, in C# 4.0 and beyond, you can also use lambda expressions to pass parameters to threads, for example:

Thread thread = new Thread(() =>
{
    string message = "Hello, World!";
    Console.WriteLine("工作线程收到参数:{0}", message);
});
thread.Start();

Using Lambda expressions can pass parameters to threads more concisely.

bannerAds