返回MemoryStream和内存泄漏的问题

时间:2014-01-07 13:17:47

标签: c# asp.net memory-leaks memorystream

我遇到了在下面的方法中处理MemoryStream的问题。你能指导一下要遵循哪一个以及为什么?

public MemoryStream FetchImageStream()
{
    try
    {
        MemoryStream imageStream = new MemoryStream();

        GetObjectResponse getObjectResponse = null; // This is NULL for example only

        using (BufferedStream bufferedStream = new BufferedStream(getObjectResponse.ResponseStream))
        {
            byte[] buffer = new byte[0x3000];
            int count;
            while ((count = bufferedStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                imageStream.Write(buffer, 0, count); // Write the image into memory stream
            }
        }
    }
    catch (Exception ex)
    {
        imageStream.Dispose();
    }       

    return imageStream;
}

=============

public void FetchImageStream(out MemoryStream imageStream)
{
    try
    {
        imageStream = new MemoryStream();

        GetObjectResponse getObjectResponse = null; // This is NULL for example only

        using (BufferedStream bufferedStream = new BufferedStream(getObjectResponse.ResponseStream))
        {
            byte[] buffer = new byte[0x3000];
            int count;
            while ((count = bufferedStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                imageStream.Write(buffer, 0, count); // Write the image into memory stream
            }
        }
    }
    catch (Exception ex)
    {
        imageStream.Dispose();
    }       

    return imageStream;
}

1:这两种方法有什么不同吗?其中一个或两个都容易发生内存泄漏。

2:在它们两者中,我们是否需要在调用它们的方法中显式地处理内存流。否则它可能会导致内存泄漏?

1 个答案:

答案 0 :(得分:2)

如果您执行以下操作,您将获得更多运气:

using (MemoryStream imageStream = new MemoryStream())
{
    imageStream = FetchImageStream(imageStream);

    if (imageStream != null)
    {
        // .... do whatever you intended to do with imageStream 
    }

} // this way, it'll be destroyed with it goes out of scope


public MemoryStream FetchImageStream(MemoryStream imageStream )
{
    try
    {
        GetObjectResponse getObjectResponse = null; // This is NULL for example only

        using (BufferedStream bufferedStream = new BufferedStream(getObjectResponse.ResponseStream))
        {
            byte[] buffer = new byte[0x3000];
            int count;
            while ((count = bufferedStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                imageStream.Write(buffer, 0, count); // Write the image into memory stream
            }
        }
    }
    catch (Exception ex)
    {
        imageStream.Dispose();

        return null;
    }       

    return imageStream;
}