Title

Thursday, 5 February 2015

Asyncclient update method is not parallel with loop connection


I have a for loop code that loop the list of IP addresses, connect to each IP,and perform update action. It is in c#.

private void cmdCommand_Click(object sender, EventArgs e)   {   List<string>[] list;   list = dbConnect.Connect(); //get list of registerd IP from database   for (int i = 0; i < list[0].Count; i++)   {   txtIPAddr.Text = list[0][i]; // Set IP to be connected   CmdConnect(txtIPAddr.Text, txtPort.Text); // Connect to IP and perform action   cmdClose(); //Close connection    }     }    private void CmdConnect(string txtIPAddr,string txtPort)   {   //connection to IP succesfull.   try   {   if (pfnCallBack == null)   {   pfnCallBack = new AsyncCallback(OnDataReceived); // refer to OnDataReceived method upon completion   }   }   catch (SocketException se)   {   MessageBox.Show(se.Message);   }   }    public void OnDataReceived(IAsyncResult asyn)   {   //perform update action    }

I have no error with the code and connection is all working well. But I have a logical error with the async method. The process update is not parallel with the IP because the AsyncCallback(OnDataReceived) method wait for the OnDataReceived completion.

So while waiting for the method to complete, I notice that the connection already loop to another IP. Therefore when OnDataReceived complete,it actually updating the wrong IP.

Is hard for me to explain the situation,therefore any conversation chat are really appreciable. Please advise.

Answer

No comments:

Post a Comment