user1465977
user1465977

Reputation: 1

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

The I/O operation has been aborted because of either a thread exist or an application request

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

Upvotes: 0

Views: 132

Answers (1)

Germann Arlington
Germann Arlington

Reputation: 3353

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.

Upvotes: 1

Related Questions