从套接字接收数据的C#性能的方法? [英] C# performance methods of receiving data from a socket?

查看:165
本文介绍了从套接字接收数据的C#性能的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我们有一个简单的互联网插座,其要送10兆字节(因为我想忽略的内存问题)通过随机数据。
是否有任何性能差异还是一个应该接收数据使用的最佳实践方法是什么?最终的输出数据应该由一个字节[]来表示。是的,我知道写入数据任意数量的内存是坏的,如果我是下载大文件,我也不会做这样的。但是,对于参数的缘故可以忽略并承担其数据量短小。我也意识到,这里的瓶颈可能不是内存管理,而是插口接收。我只是想知道什么是接收数据的最有效的方法。

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. 有一个列表和一个缓冲,后缓冲区已满,将其添加到列表中,并在年底list.ToArray()来获得的byte []

  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[]

写缓存到内存流,其完整的结构后stream.Length的一个byte [],为了得到字节[阅读全部内容进去]输出。

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?

推荐答案

刚写入​​的MemoryStream ,然后调用的 的ToArray - ,做构建业务一个大小合适的字节数组你。这是有效的什么列表<字节方式> 会是什么样反正,但使用的MemoryStream 将是一个简单得多

Just write to a MemoryStream and then call ToArray - that does the business of constructing an appropriately-sized byte array for you. That's effectively what a List<byte> would be like anyway, but using a MemoryStream will be a lot simpler.

这篇关于从套接字接收数据的C#性能的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆