I need to use Asynchronous Socket functions in a server application and
am learning from sources such as the MSDN2
(http://msdn2.microsoft.com/en-us/library/bbx2eya8.aspx). What I
observed is that all callback handlers in examples are static
functions. I did try non-static callback handlers; they certainly
works, and they usually make my code simpler.
For example, a typical tutorial will start an asynchronous connection
with:
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback),
client );
and handle the results with:
static void ConnectCallback(IAsyncResult ar) {
...
}
Because we cannot directly refer to any class member variables and
functions in a static function, we will have to pack them into the "ar"
parameter and pass them to the callback handler. In the above example,
we passed the caller of the BeginConnect() function as the "ar", so we
can get it back with "ar.AsyncState".
On the other hand, if non-static callback handlers are used, I usually
don't need to pass anything in "ar". In the above example, I will be
able to directly use the "client" in the ConnectCallback() (My
BeginXXX() and handlers are in the same class).
Can somebody please let me know if there will be any performance
penalties if I go with the non-static callbacks? What was the reason
for the penalties if there are any?
I am also curious about how expensive the "new" operation, that coverts
a callback function name to an AsyncCallback delegate, is. In case of
reading and writing, my sever will need to process lots of them. So I
am thinking of creating a member variable to hold the function
references for the lifetime off an object.
Any input will be very appreciated,
Jimmy