How to pass parameters in a C# thread?

In C#, you can use the ParameterizedThreadStart delegate to pass parameters to a thread. Here is an example:

using System;
using System.Threading;

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

        Console.WriteLine("主线程结束。");
    }

    static void WorkerThread(object data)
    {
        // 从参数中获取数据
        string message = (string)data;

        // 执行线程的工作
        Console.WriteLine("子线程开始执行,传递的参数为:" + message);

        // 模拟一些工作
        Thread.Sleep(2000);

        Console.WriteLine("子线程结束。");
    }
}

In the example above, we created a new thread and associated the WorkerThread method with it using the ParameterizedThreadStart delegate. The WorkerThread method receives a parameter of type object when executed, and we use the data by converting the parameter to the appropriate type.

Please note that when using the ParameterizedThreadStart delegate to pass parameters, the type must be of object type, so appropriate type conversion may be required before using them.

bannerAds