C# performance methods of receiving data from a socket?

Posted by Daniel on Stack Overflow See other posts from Stack Overflow or by Daniel
Published on 2010-04-06T06:02:30Z Indexed on 2010/04/06 6:13 UTC
Read the original article Hit count: 246

Filed under:
|
|

Lets assume we have a simple internet socket, and its going to send 10 megabytes (because i want to ignore memory issues) of random data through. Is there any performance difference or a best practice method that one should use for receiving data? The final output data should be represented by a byte[]. Yes i know writing an arbitrary amount of data to memory is bad, and if I was downloading a large file i wouldn't be doing it like this. But for argument sake lets ignore that and assume its a smallish amount of data. I also realise that the bottleneck here is probably not the memory management but rather the socket receiving. I just want to know what would be the most efficient method of receiving data.

A few dodgy ways can think of is:

  1. Have a List and a buffer, after the buffer is full, add it to the list and at the end list.ToArray() to get the byte[]

  2. Write the buffer to a memory stream, after its complete construct a byte[] of the stream.Length and read it all into it in order to get the byte[] output.

Is there a more efficient/better way of doing this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about socket