tianyi
tianyi

Reputation: 109

Is it worth to pool SocketAsyncEventArgs for reuse in this scenario?

In my scenario, there are many clients' tcp sockets connected to the server.The server ReceiveAsync() from all sockets and when the callback is called without error, parse the received data. If one socket's received data is an certain type of message , the receive callback will SendAsync() to all other sockets by a loop,and then start to ReceiveAsync() again. So for one socket, it has chance to call SendAsync() by many other Receivers'callback in a very short time. I tried to synchronize the Sendings by waitone semaphore and release one semaphore after the sending IO completed so I can use only one SAEA obj for each socket, but this may cause the receiver's callback block in the sending loop . So I canceled the semaphore and pooled some SAEA objs for each socket's sending method. However I found that some mobile-phone clients have big chance to lost there IP connection and there socket SendAsync() methods ' error callbacks will not be called promptly.Perhaps in several minutes, no SAEA will be recycled to the pool.

Another question is, if I pool the reusable SAEA, will the SAES.Buffer make memory fragments? Can I avoid the memory problem by calling SAEA.SetBuffer(null,0,0) method before pooling the SAEA?

Upvotes: 3

Views: 1158

Answers (1)

Markus Müller
Markus Müller

Reputation: 2641

To avoid memory fragmentation we use one giant buffer and assign a certain region of this buffer to each SAEA. So memory usage stays the same during the whole time and memory is allocated continuously.

Right now we use pooled SAEAs which can be a PITA, but it seems to be the most advocated solution (if you use SAEAs at all that is)

Upvotes: 0

Related Questions