简体   繁体   English

我有这段代码可以在C#中连接UDPClient,请问有人可以吗?

[英]I have this code to connect UDPClient In C#, Please Can Any one Tell me It is fine or not?

Here Is My Code. 这是我的代码。 I have written this code to Receive The Messages from the client in a Separated Thread. 我已将此代码编写为在单独的线程中从客户端接收消息。 What I want to ask is, Is This fine as compared to using async callback methods. 我想问的是,与使用异步回调方法相比,这还好吗?

private void button1_Click(object sender, EventArgs e)
    {
        //Start Receiving Messages from Clients
        remoteEP = new IPEndPoint(IPAddress.Any, 4510);
        serverThread = new Thread(new ThreadStart(ServerThreadMethod));
        serverThread.Start();
    }

    private void ServerThreadMethod()
    {
        while (true)
        {
            var data = udpServer.Receive(ref remoteEP); // listen on port 11000
            string rec_data = Encoding.UTF8.GetString(data);

            this.BeginInvoke((ThreadStart)delegate()
            {
                lblStatus.Text = rec_data + " -> receive data from " + remoteEP.ToString();
            }
            );
            Thread.Sleep(1000);
        }
    }

Is this fine as compared to using async callback methods? 与使用异步回调方法相比,这还好吗?

"Fine" according to what standard or point of view? “精细”根据什么标准或观点?

IMHO, network I/O should always be done with asynchronous methods. 恕我直言,网络I / O应该始终使用异步方法来完成。 .NET offers a large number of viable options for doing so, and they are all more efficient than dedicating a single thread to each socket. .NET为此提供了许多可行的选择,并且它们比将单个线程专用于每个套接字更有效。

That said, other than the pointless call to Thread.Sleep(1000); 就是说,除了对Thread.Sleep(1000);的无意义的调用之外Thread.Sleep(1000); , which you should remove, and the anomalous use of the ThreadStart delegate type instead of MethodInvoker (the latter is documented as being more efficient), the code you have looks "fine", from the point of view that it should work for small numbers of sockets and clients. ,您应该删除它,并以异常的方式使用ThreadStart委托类型而不是MethodInvoker (后者被记录为更有效),从它应该适用于小数的角度来看,您的代码看起来“不错”套接字和客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM