I have a Form (Form1) that has implemented asynchronous TCP/IP sockets. I have an object(public class MyObject) that I created.
From the Form, I create a array of MyObjects. I then call methods on MyObjects for manipulating data. In MyObjects I have a function:
private void send(string sPacketData)
{
if (SocketState.clientSocket != null && SocketState.clientSocket.Connected)
{
byte[] byteData = Encoding.ASCII.GetBytes(sPacket);
SocketState.clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(Form1.SendCallback), this);
}
}
The problem here is that I am trying to access Form1’s SendCallback function with no reference to Form1.
Here is what SendCallback looks like:
public void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
MyObject mo = (MyObject)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = mo.SocketState.clientSocket.EndSend(ar);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Send Callback: " + e.Message + "\r\n");
}
}
One solution would be to make SendCallback static, but this leads to exceptions where the is not set to an instance of an object.
Is there a different way to do this? Am I barking up the wrong tree? Should I be returning the data I want to send from MyObjects’s function calls and then sending from the Form?
Just have
sendtake the callback as one of it’s parameters, and haveform1pass in the callback method tosend. Alternatively, you could add a property toMyClassof typeAsyncCallbackwhich is set byForm1and used in thesendmethod.When creating the callback in
Form1to pass toMyObjectusethis.SendCallbackrather thanForm1.SendCallback. Or, sincethisis implied, just put inSendCallback.A delegate isn’t just a reference to a method, it’s a reference to a method and an object instance that should call it (which is much more powerful). (The object will be
nullfor static methods.) Fortunately, you don’t need to explicitly pass the reference to the delegate constructor. When you enterthis.SomeMethodorsomeObject.MethodOfThatObjectthe compiler will translate it into a delegate to that method called on that instance.