C# uses delegation to update the main window control display in the Socket Udp port listening thread

c# opens the thread to listen to the Socket UDP port. After the port receives the card reading data from the network card reader, refreshes the UI interface to display the received data, parses the data packet information and sends the display text to the card reader, and drives the card reader to broadcast voice and beep Sound prompts, turn on the relay switch and other operations.

This example uses the device introduction:

1. After swiping the card, upload the card number, machine number and other information to the designated remote server IP and port through UDP protocol

2. Receive and respond to the display text, buzzer sound, TTS Chinese voice broadcast, switch relay and other commands sent by the remote server.

WIFI wireless network RFID cloud card reader remote network switch logistics network NB-IoT4G card reader - Taobao.com (taobao.com)

   .net hints that by setting: CheckForIllegalCrossThreadCalls = false, you can force update the control values ​​in the main window in the sub-thread to refresh the UI display, but sometimes the display information will not be refreshed in time, causing the display to freeze, or the software to crash directly, etc. Question, some data shows that Microsoft does not recommend using this kind of sub-thread to force the UI display to be refreshed. It is strongly recommended to use the delegate method to refresh the UI display. The code is as follows:

Define the delegate and transfer parameters:

delegate void Update1(string text1, byte[] bytes, int byteslen);   //UDP端口侦听线程内解析接收到的数据并更新UI委拖
delegate void Update2(string text1, string msg);                   //UDP端口侦听线程内更新UI委拖
复制代码

Open the Socket Udp listening port and start the listening thread:

        private void StartListener()
        {
            IPEndPoint LocalPoint;
            PortNumber = Convert.ToInt32(textBox23.Text);
            while (!ready)
            {
                try
                {
                    LocalPoint = new IPEndPoint(IPAddress.Parse(localIp), PortNumber);
                    ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    ListenerSock.Bind(LocalPoint);

                    ListenerThre = new Thread(new ThreadStart(ThrListener));
                    ListenerThre.Start();
                    ready = true;
                }
                catch
                {
                    ListenerSock.Close();
                    ready = false;
                    MessageBox.Show("有其它应用程序占用了 " + PortNumber.ToString() + " ,请检查并关闭此应用后再打开本程序", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(0);                      //这是最彻底的退出方式,不管什么线程都被强制退出,把程序结束的很干净。
                }
            }
        }

        public void ThrListener()
        {
            while (ready)
            {
                try
                {
                    EndPoint RemotePoint = new IPEndPoint(System.Net.IPAddress.Any, 0);
                    byte[] bytes = new byte[1024];
                    int NumGet = ListenerSock.ReceiveFrom(bytes, ref RemotePoint);
                    RemoteIPoint = (IPEndPoint)RemotePoint;                                 //获取数据包来源IP及端口,原路回应

                    string dispstr = DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") + (" FromIP:" + Convert.ToString(RemotePoint) + "          ").Substring(0, 30) + "Data:";
                    this.BeginInvoke(new Update1(EditUi1), dispstr, bytes, NumGet);        //通过委托传送参数显示接收到的数据包,并根据情况回应设备            
                }
                catch (Exception ex)
                {
                    this.BeginInvoke(new Update2(EditUi2), DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") + " ", ex.Message);   //通过委托传送参数显示接收到的数据            
                }
            }
        }
复制代码

Delegate to update UI display

private void EditUi1(string text1, byte[] buf, int buflen) //Update UI through delegation, array transfer parameters
{            
            int i;
            string recestr = "";//Receive data display

            for (i = 0; i < buflen; i++)
            {                 recestr = recestr + buf[i].ToString("X2") + " ";             }             ListItemAdd(text1 + recestr); } private void EditUi2(string text1, string Msg ) //Update UI through delegation, string transfer parameters {      ListItemAdd(text1 + Msg); }


            

            

         



Guess you like

Origin blog.csdn.net/zhangjin7422/article/details/129101522