处理后调用 MemoryStream.ToArray() 是否危险?

Is calling MemoryStream.ToArray() dangerous after disposing?(处理后调用 MemoryStream.ToArray() 是否危险?)
本文介绍了处理后调用 MemoryStream.ToArray() 是否危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在下面的代码中,GC 是否有可能清除 MemoryStream 从而使 ToArray 失败,因为它在 using 语句之外?

In the below code, is there any chance the GC will clean out the MemoryStream so that ToArray will fail, since it is outside the using statement?

private static byte[] getBytes()
{
    MemoryStream ms = null;

    using (ms = new MemoryStream())
    {
        // ...
    }

    return ms.ToArray();
}

推荐答案

不,没有机会.这样做是安全的 - MemoryStream 保持对字节数组的强引用.

No, there's no chance of that. It's safe to do - the MemoryStream keeps a strong reference to the byte array.

我会看看我是否能找到任何关于保证的文件...

I'll see if I can find any documentation about guarantees...

有点……

来自 MemoryStream.Close:

一旦流关闭,缓冲区在 MemoryStream 上仍然可用.

The buffer is still available on a MemoryStream once the stream has been closed.

诚然,这并不能保证 Dispose 的实现,但已记录为调用 Stream.Close.

Admittedly that doesn't guarantee it for Dispose, but that's documented to call Stream.Close.

MemoryStream.Dispose(bool) 可以然后被覆盖以释放数组,但在我的经验中不是这样,这将是一个突破性的变化点.

MemoryStream.Dispose(bool) could then be overridden to release the array, but it doesn't in my experience, and it would be a breaking change at this point.

这篇关于处理后调用 MemoryStream.ToArray() 是否危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)
Why do I get quot;error: ... must be a reference typequot; in my C# generic method?(为什么我会收到“错误:...必须是引用类型?在我的 C# 泛型方法中?)