为什么 MemoryStream Position 属性会随着 SetLength 的变化而变得不可变?
使用 System.IO.MemoryStream 类时出现问题。
创建后,如下所示:
var memory = new MemoryStream();
然后设置要写入其中的一些字节的长度。
var length = 181;
memory.SetLength( length);
然后在调试器中,内存显示长度和 位置 BOTH 设置为 181。在单独的简单测试程序中 它属性显示 SetLength()
之后 Position 仍为零。
此外,如果我使用以下命令将 Position
属性更改为 0 调试器或通过添加一行代码,它会忽略 并且仍然显示 181 作为位置属性。因此它 表现得好像是不可变的。
然而,在一个简单的单元测试中,这再次按预期工作。
起初,这似乎是一个线程问题,因为 如果 MemoryStream 不是线程安全的。但在调试器中, 在调用任何这段代码之前,我冻结了所有其他线程。 而且还是如上面那样失败。
嗯,这是最奇怪的。有什么想法可以尝试吗?
There's trouble using the System.IO.MemoryStream class.
After creating it, like so:
var memory = new MemoryStream();
it then sets the length of some bytes to write into it.
var length = 181;
memory.SetLength( length);
Then in the debugger, the memory shows the Length and
Position BOTH set to 181. In separate simply test program
it property shows Position still at zero after SetLength()
.
Furthermore, if I change the Position
property to 0 using
the debugger or by adding a line of code, it ignores
and still shows 181 as the position property. Thus it
behaves as if immutable.
However, again in a simple unit test, this works as expected.
At first, this appeared to be a threading issue as
if MemoryStream isn't thread safe. But in the debugger,
I froze all other threads before calling any of this code.
And it still fails as above.
Well, this is the most bizarre. Any ideas what to try?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我和你看到的不一样。如果我在 Main: 中使用以下代码创建一个控制台应用程序:
..并跟踪对
SetLength
的调用,调试器会显示Length
等于 181 且Position< /code> 等于 0。您必须有其他东西影响您的流对象。
I don't see the same thing as you. If I create a console application with the following code in Main:
..and trace past the call to
SetLength
, the debugger showsLength
equal to 181 andPosition
equal to 0. You must have something else affecting your stream object.其实,已经找到问题所在了。第一个线索是它只发生在调试器中。
原因是 ToString() 方法被重写。
它正在读取内存并将其显示在调试器中。那是从内存中读取并因此修改位置。
问题解决了。
谢谢。
Actually, figured out the problem. First clue was that it only happened in the debugger.
The cause was the the ToString() method was overridden.
It was reading the memory and displaying it in the debugger. That was reading from the memory and therefore modifying the Position.
Problem solved.
Thanks.