0

当我尝试通过单击表单右侧的“X”关闭应用程序时遇到问题我收到一条错误消息

由于线程存在或应用程序请求,I/O 操作已中止

我得到了这行代码:

newsocket.EndReceiveFrom(ar,ref tmp);

这是我的代码示例:

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];
            }
        }
    }
}
4

1 回答 1

1

您的

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

接收器线程在后台运行,我没有看到任何可以处理表单卸载和接收器线程正常关闭的代码。这就是您需要做的 - 当您关闭表单时停止您的线程(您需要将线程引用存储在您的类变量中)。

于 2012-08-17T08:32:43.833 回答