Reputation: 6208
I've been working with the .NET 3.5 asynchronous socket API and found that ll 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?
Upvotes: 1
Views: 1242
Reputation:
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.
Upvotes: 2