• 线程里面添加参数,并解决多个参数问题[原创]


    线程默认的ThreadStart委托只能使用void方法,但是Thread有个扩展委托ParameterizedThreadStart,可以传递object类型。比如下面这个:

     1 publicstaticvoid ServerReceive(object parmas)
    2 {
    3 TcpParmater vals = parmas as TcpParmater;
    4 IPAddress ServerIp = GetServerIP();
    5 IPEndPoint iep =new IPEndPoint(ServerIp, 10086);
    6 socket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    7 socket.Connect(iep);
    8
    9 byte[] byteMessage =newbyte[1024];
    10 socket.Bind(iep);
    11 while (true)
    12 {
    13 try
    14 {
    15 socket.Listen(5);
    16 Socket newSocket = socket.Accept();
    17 newSocket.Receive(byteMessage);
    18 newSocket.Send(byteMessage, byteMessage.Length, 0);
    19 TMessage message =new TMessage();
    20 message.IpAddr = newSocket.RemoteEndPoint.ToString();
    21 message.Msg = Encoding.Default.GetString(byteMessage);
    22 message.AddTime = DateTime.Now.ToShortTimeString();
    23 vals.todo(message);
    24 }
    25 catch
    26 {
    27 }
    28 }
    29 }

      

    TcpParmater是我定义的一个类,用来存放参数,上面我还实例化了一个委托,因为需要在方法里插入一个方法

     1 publicclass TcpParmater
    2 {
    3 publicstring hostname;
    4
    5 ///<summary>
    6 /// 接收数据后处理事件委托
    7 ///</summary>
    8 ///<param name="message"></param>
    9 publicdelegatevoid dosomthing(TMessage message);
    10
    11 public dosomthing todo;
    12 }

      

    线程使用如下:

    1  TcpParmater paras =new TcpParmater();
    2 paras.hostname ="192.168.100.102";
    3 paras.todo = show;
    4 Thread tclient =new Thread(new ParameterizedThreadStart(TcpSocket.ClientReceive));
    5 tclient.Start(paras);

    我创建了一个对象paras,作为ClientReceive的参数。这样就OK了

    这里其实有两个问题,1.线程传值(ParameterizedThreadStart解决),2.多参数问题(参数放到一个类里)。

  • 相关阅读:
    C#构造函数
    C#析构函数
    C#常量
    C#属性
    checklistbox的用法
    2012快捷键
    查询ORACLE存储关联表
    UltraDropDown
    Linux常用命令大全(非常全!!!)
    infra 仪表盘效果
  • 原文地址:https://www.cnblogs.com/405464904/p/2165515.html
Copyright © 2020-2023  润新知