views:

197

answers:

1

Hi everyone,

I've been working with the "new" (3.5, I think?) asynchronous socket API and have a question or two about it that I can't find answers to.

All of the *Async methods return a bool, which is false if the operation completed synchronously. I'm a little confused as to how/why this could happen. It's not always an error condition, right? The MSDN examples immediately call the event handler manually in this case. Is that a good practice to follow?

Additionally, when I call Socket.SendAsync for instance, and attach a handler to SocketAsyncEventArgs.Completed, am I guaranteed that "Completed" is fired (or SendAsync returns false) only after all of my data has been sent? Or is it possible that it will call my handler somewhere in the middle?

+2  A: 

It may return synchronously if the action requested can be preformed instantly, for instance, if the TCP Buffer already contains the data required to complete the ReceiveAsync method, or a client is already waiting to be accepted ect.

The examples the handler because the AsyncMethod will not. I would be happy to use invoke the handler directly in this case (if there is only one subscribing). However there is a practice which suggests that you shouldn't, rather that the handler should not do anything except call another method (posibly with more meaningful params) which handles the logic - and that you should invoke this method rather than the actual event/handler.

The event will not be raised before the operation completes, Unless of course you do it manually when the async method returns true (is not complete).

From MSDN:

Returns true if the I/O operation is pending. The SocketAsyncEventArgs.Completed event on the e parameter will be raised upon completion of the operation.

Returns false if the I/O operation completed synchronously. In this case, The SocketAsyncEventArgs.Completed event on the e parameter will not be raised and the e object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation.

Courtney de Lautour
When you say "the operation completes" (for SendAsync), does "complete" mean that the entire buffer of data (that you specify) has been sent? Inuitively, semantically, I am thinking "of course", but I just want to be absolutely positive.
Sapph
Yeap, for that instance of SocketAsyncEventArgs. Perhaps the Socket.BeginXYZ / Socket.EndXYZ methods would be nicer (no need to worry about completing synchronously - although that info is passed to the callback aswell)
Courtney de Lautour
Thank you, good to know. :)
Sapph