Non-static member method as AsyncCallback

J

JohnnieB

Hi,

I'm writing a server application that uses asynchronous I/O. In all
examples I've seen a state object, typically a class with just data
members, is used to store the socket that's used in conjunction with
BeginReceive and the callback method is declared static.

I ended up using following approach instead, see below. That is, member
method of the class itself is used as callback and all state is stored
in member variables of the class. State object passed to BeginReceive
is null because it's not needed. This is much more convenient way in my
opinion.

public class RequestHandler
{
private Socket socket;
private byte[] buffer;

public RequestHandler(Socket s)
{
socket = s;
buffer = new byte[1024];
}

public void Start()
{
socket.BeginReceive(buffer, 0, 1024, SocketFlags.None, new
AsyncCallback(this.OnRecv), null);
}

private void OnRecv(IAsyncResult ar)
{
try
{
int bytesRead = socket.EndReceive(ar);
// do something with the received data
// Continue receiving more
socket.BeginReceive(buffer, 0, 1024, SocketFlags.None, new
AsyncCallback(this.OnRecv), null);
}
}
}

My question is, could this approach cause problems in the long run? I
don't fully get it how the non-static OnRecv callback method resolves
the class instance whose data it is to modify. But, it just seems to
work.
 
J

Jon Skeet [C# MVP]

My question is, could this approach cause problems in the long run? I
don't fully get it how the non-static OnRecv callback method resolves
the class instance whose data it is to modify. But, it just seems to
work.

The delegate remembers not only which method needs to be called, but
the target on which to call the method. That's how it works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top