C# 向线程中传入多个参数的几种方法

1.使用匿名方法或 Lambda 表达式:

Thread clientThread = new Thread(() => HandleClient(clientSocket, param1, param2));
clientThread.Start();

// 处理方法
static void HandleClient(Socket clientSocket, int param1, string param2)
{
    // 处理逻辑
}

2.使用自定义类封装参数:

class ClientParams
{
    public Socket ClientSocket { get; set; }
    public int Param1 { get; set; }
    public string Param2 { get; set; }
}

// 创建线程
ClientParams parameters = new ClientParams 
{ 
    ClientSocket = clientSocket, 
    Param1 = 10, 
    Param2 = "测试" 
};
Thread clientThread = new Thread(HandleClient);
clientThread.Start(parameters);

// 处理方法
static void HandleClient(object obj)
{
    ClientParams parameters = (ClientParams)obj;
    Socket clientSocket = parameters.ClientSocket;
    int param1 = parameters.Param1;
    string param2 = parameters.Param2;
    
    // 处理逻辑
}

3. 使用元组(C# 7.0及以上版本):

var parameters = (clientSocket, param1: 10, param2: "测试");
Thread clientThread = new Thread(() => HandleClient(parameters));
clientThread.Start();

// 处理方法
static void HandleClient((Socket socket, int param1, string param2) parameters)
{
    Socket clientSocket = parameters.socket;
    int param1 = parameters.param1;
    string param2 = parameters.param2;
    
    // 处理逻辑
}

4.使用 ParameterizedThreadStart 委托(仅适用于单个对象参数):

object[] parameters = new object[] { clientSocket, 10, "测试" };
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClient));
clientThread.Start(parameters);

// 处理方法
static void HandleClient(object obj)
{
    object[] parameters = (object[])obj;
    Socket clientSocket = (Socket)parameters[0];
    int param1 = (int)parameters[1];
    string param2 = (string)parameters[2];
    
    // 处理逻辑
}

  

posted @ 2024-07-25 15:11  尼古拉-卡什  阅读(221)  评论(0编辑  收藏  举报