简体   繁体   English

UDP连接出错

[英]Getting error in UDP connection

I am having a problem when I try to close the application by clicking the 'X' which is on the right side of the form I am getting an error which says 我在尝试通过单击表格右侧的“ X”来关闭应用程序时遇到问题,出现错误提示

The I/O operation has been aborted because of either a thread exist or an application request 由于存在线程或应用程序请求,I / O操作已中止

And I am getting at this line of code: 我得到的是这一行代码:

newsocket.EndReceiveFrom(ar,ref tmp);

Here is the example of my code : 这是我的代码示例:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int m;
        Socket newsocket;    
        EndPoint tmp;
        IPEndPoint sen = new IPEndPoint(IPAddress.Loopback, 5001);
        byte[] data = new byte[1024];
        byte[] buffer = new byte[1024];

        public Form1()
        { 
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) 
        {
            CheckForIllegalCrossThreadCalls = false;
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1235);
            newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);
            newsocket.Bind(endpoint);
            tmp = (EndPoint)sen;
            newsocket.BeginReceiveFrom(data, 0, 40, SocketFlags.None,ref tmp, new AsyncCallback(ReadCallback), tmp);
            Thread thread = new Thread(new ThreadStart(this.threadtask));
            thread.Start();
        }

        protected void ReadCallback(IAsyncResult ar) 
        {
            newsocket.EndReceiveFrom(ar,ref tmp);
            send();
            newsocket.BeginReceiveFrom(data, 0, 40, SocketFlags.None, ref tmp, new AsyncCallback(ReadCallback), tmp);
        }

        private void send()
        {
            newsocket.BeginSendTo(buffer, 0, 7, SocketFlags.None, sen, newAsyncCallback(SendCallback), sen);
        }

        protected void SendCallback(IAsyncResult ar)
        {
            newsocket.EndSendTo(ar);
        }

        private void threadtask()
        {
            while (true)
            {
                cMicroLCCore.getDAC(m).Value = data[m];
            }
        }
    }
}

Your 你的

Thread thread = new Thread(new ThreadStart(this.threadtask));
thread.Start();

receiver thread is running in background, I don;t see any code which would handle form unload and graceful closing of your receiver thread. 接收器线程在后台运行,我看不到任何可以处理表单卸载和正常关闭接收器线程的代码。 That is what you need to do - stop your thread (you will need to store thread reference in your class variable) when you are closing the form. 那就是您需要做的-在关闭表单时停止线程(您需要将线程引用存储在类变量中)。

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

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