MemoryStream 使用了太多内存并且没有 dispose/close

MemoryStream uses too much memory and doesn't dispose/close

内存使用率上升,直到遇到 System.OutOfMemory 异常。 MemoryStream 实例计数也会增加,直到发生异常。我尝试使用 using(),做 ms.Dispose(),ms.Close(),还有一些其他的,GC.Collect() 等。 这可能是内存泄漏吗?

  while(running){ 
var screen = Screen.PrimaryScreen;
                using(Bitmap bitmap = new Bitmap(screen.Bounds.Width, screen.Bounds.Height)) {
                    using(var g = Graphics.FromImage(bitmap)) {
                        g.CopyFromScreen(screen.Bounds.Left, screen.Bounds.Top, 0, 0, screen.Bounds.Size);
                    }
                    using(EncoderParameters encoderParams = new EncoderParameters(1)) {
                        encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ssQuality);
                        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
                        ImageCodecInfo jgpEncoder = codecs[1];
                        using(var ms = new MemoryStream()) {
                            bitmap.Save(ms, jgpEncoder, encoderParams);
                            image img2 = new image();
                            img2.Img = Image.FromStream(ms);
                            binF.Serialize(client.GetStream(), img2);
                        }
                    }
                }
}

VS 内存视图:

进程的任务管理器内存使用情况:

您需要处理从 Image.FromStream(ms); 返回的图像,例如像这样:

ms.Position = 0; // Rewind the stream.
using (var image2 = Image.FromStream(ms)) 
{ 
    image img2 = new image { Img = image2 };
    binF.Serialize(client.GetStream(), img2);
}

这将确保不仅第二个图像的资源被及时处理,而且 MemoryStream ms 更有可能被及时垃圾收集。目前没有发生,因为 Image 保留对创建它的流的引用。 docs 中提到了这一点:

You must keep the stream open for the lifetime of the Image.