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


    线程默认的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.多参数问题(参数放到一个类里)。

  • 相关阅读:
    Pearls POJ 1260 DP
    The Cow Lexicon DP
    矩形嵌套
    POJ 3061 Subsequence 尺取
    动物统计加强版 Trie 树
    codevs 1422 河城荷取
    cogs 944. [東方S3] 藤原妹红
    codevs 2830 蓬莱山辉夜
    cogs 998. [東方S2] 帕秋莉·诺蕾姬
    cogs 920. [東方S1] 琪露诺
  • 原文地址:https://www.cnblogs.com/405464904/p/2165515.html
Copyright © 2020-2023  润新知