本文介绍了处理后调用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...

编辑:有点...

来自:

不能保证在 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()危险吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:23