When will MemoryStream.TryGetBuffer return a useful ArraySegment?

放肆的年华 提交于 2019-12-23 07:16:10

问题


bool MemoryStream.TryGetBuffer(out ArraySegment<byte> buffer) is a new API in .NET 4.6 that can be used to get access to the valid bytes stored in the MemoryStream without copying them. This is very exciting! It returns a bool that is "true if the conversion was successful; otherwise, false" and populates the out param.

When does it return true, indicating that the out ArraySegment<byte> buffer now contains valid information? This isn't documented today.

I know that if it returns false, I can use .ToArray() to get a copy of the bytes. And, we've have .GetBuffer(), but sometimes MemoryStreams are created with an offset into the buffer, and this information is hard (well, sort of) to get later on, not to mention the try ... catch needed for robustness.


回答1:


For TryGetBuffer to perform a successful conversion and populate the out param with useful information, the buffer must be visible. The buffer is visible if any of these constructors are used:

  • MemoryStream()
  • MemoryStream(int capacity)
  • MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) with publiclyVisible: true.

Check the source code for more details.




回答2:


GetBuffer return all bytes in memory, independent of use,

ex: Capacity = 100000, Length = 200

GetBuffer (and TryGetBuffer !?) return bytes( Capacity )

ToArray return bytes( Length )



来源:https://stackoverflow.com/questions/30808289/when-will-memorystream-trygetbuffer-return-a-useful-arraysegment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!