Bogdan Varlamov (a.k.a. Phantom Stranger)

Minimize Asynchronous Socket Callbacks With Dynamic Buffer Sizes


by Bogdan Varlamov (a.k.a. Phantom Stranger)

I've been doing a lot of work with .NET Sockets lately, and I will be posting more articles discussing what I've been working on in greater detail. In this article, I want to talk about the concept of reading a Socket asynchronously, raising events to notify your application when bytes are received, and minimizing the number of times the callback method is processed.

If you are familiar with .NET Sockets you might already know that there are asynchronous methods to receive bytes from Sockets (Microsoft has an Asynchronous Server Socket Example available if you are interested in seeing code for doing this).

In the above code sample, a StateObject class that contains a byte buffer with a static size is passed around. When the asynchronous socket read happens, incoming bytes are stored into this buffer and then passed back to the receive callback method. This example works fine, but I think there are some optimizations that can be applied.

Would you like to know more?