I am dealing with a strange problem when closing a socket connection. I am using an asynchronous receive and I specified, as is MSDN's suggestion, a user-defined object as the last parameter in my BeginReceive(). I expect, as MSDN says, this same object to be passed in the State field of the IAsynchResult parameter of the Callback function I specified in my BeginReceive () call. But , as I close the connection, and the tcp layer as usual sends me a zero-length packet, the Callback function is called but the State field is the Socket native object which received the close and not the user-defined object I specified in the BeginReceive.
This seems to be in contrast with MSDN specifications. What am I doing wrong ?
Well, it would help if you posted some code - in particular, the call to BeginReceive(), and the corresponding callback method.
Are you sure you've passed the right object and that you're checking in the right callback, or that there aren't any other methods invoking the same callback, possibly sending a Socket instead, and you don't expect it?
Take a look at the MSDN example at this page.
Here's the condensed version:
// some class that holds some user data, like the socket, or the buffer, and whatever
public class StateObject
// A listen callback, invoked by BeginAccept(), which passed a socket as user state object
public static void Listen_Callback(IAsyncResult ar)
Socket s = (Socket) ar.AsyncState; // retrieve the socket (normally, you know what type to cast to)
Socket s2 = s.EndAccept(ar); // end operation, get the new socket
StateObject state = new StateObject(); // create and init the StateObject instance
state.workSocket = s2;
s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE,0,
new AsyncCallback(Read_Callback), state); // and pass it instead
// the read callback retrieves the StateObject instance
public static void Read_Callback(IAsyncResult ar)
StateObject state = (StateObject) ar.AsyncState;
Last edited by TheGreatCthulhu; August 1st, 2012 at 07:36 AM.