C# - MemoryStream,循环中 image.Save - 随机保护内存错误

C# - MemoryStream, image.Save in a loop - random protected memory error

在抓取图像(Image 类型)以在一种循环中将它们转换为 "Base64 String" 时,我总是在随机执行时遇到此错误。

"Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

        private void doCapture()
        {
            CaptureInfo.CaptureFrame();
        }

        void CaptureInfo_FrameCaptureComplete(PictureBox Frame)
        {
            string str = toB64img(Frame.Image);
            //do something with the string
            this.doCapture();
        }

        private string toB64img(Image image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, ImageFormat.Png);   <==== error HERE
                byte[] imageBytes = ms.ToArray();
                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

图片来自directx.capture,网络摄像头拍摄。 (工作正常) 我假设那是因为某些东西仍在访问中并且尚未关闭,所以错误原因已经在使用中。但是我该如何解决这个问题?

我的想法是对的。 有些东西释放得不够快。 在函数的 RETURN 之前添加一个强制 GC 检查,就像一个魅力......奇怪。

private string toB64img(Image image)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, ImageFormat.Png);   
            byte[] imageBytes = ms.ToArray();
            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            GC.Collect();                       <======
            GC.WaitForPendingFinalizers();      <======
            GC.Collect();                       <======
            return base64String;
        }
    }

``