接收UDP广播时应用程序冻结 [英] Application freezes when receiving UDP broadcasts

查看:88
本文介绍了接收UDP广播时应用程序冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在LAN中接收UDP广播
这是我的代码:

Im trying to receive UDP Broadcasts IN A LAN
This is my code:

private void timer1_Tick(object sender, EventArgs e)
        {
            EndPoint iep = new IPEndPoint(IPAddress.Any, 0);
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000);
            listener.Bind(localEndPoint);
            EndPoint ep = (EndPoint)iep;
            this.Text = "Ready to receive…";
            byte[] data = new byte[1024];
            int recv = listener.ReceiveFrom(data, ref ep);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            
            listBox1.Items.Add(stringData);
            listener.Close();
        }



现在发生的事情是由于计时器造成的,我的应用程序冻结了
尽管它接收广播并将数据添加到列表框中.
有什么办法可以确保仍然接收到UDP广播,同时又不会冻结应用程序?



Now what happens is due to the Timer, my application freezes
though it receives the broadcasts and adds the data to the list box.
Is there any way that i can make sure that the UDP broadcasts are still received, at the same time doesn''t freeze the application?

推荐答案

也许您可以创建侦听器/广播处理程序代码的单独线程,以便不阻塞UI线程?
Perhaps you could create a separate thread for the listener/broadcast handler code so that it''s not blocking the UI thread?


这篇关于接收UDP广播时应用程序冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆