|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Non-static member method as AsyncCallbackI'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. JohnnieB <z**@users.easynews.com> wrote:
<snip> > My question is, could this approach cause problems in the long run? I The delegate remembers not only which method needs to be called, but > 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 target on which to call the method. That's how it works. -- Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet If replying to the group, please do not mail me too |
|||||||||||||||||||||||