使用内存流时,出现了“System.OutOfMemoryException”类型的异常。这是C#中的一个问题。

3
我正在使用WPF应用程序,并且在其中使用内存流写入方法来编写DICOM数据字节。当试图编写大小超过70 MB的大型DICOM数据时,它会显示类型为System.OutOfMemoryException的异常。请问是否有任何解决方法。
代码片段如下:
try
            {
                using ( MemoryStream imagememoryStream = new MemoryStream())
                {
                    while (true)
                    {
                        // Retrieve the DICOMData.
                        // data comes as chunks; if file size is larger, multiple RetrieveDICOMData() calls
                        // has to be raised. the return value specifies whether the chunk is last one or not.                  
                        dicomData = dicomService.RetrieveDICOMData( hierarchyInfo );
                        imagememoryStream.Write( dicomData.DataBytes, 0, dicomData.DataBytes.Length );
                        if (dicomData.IsLastChunk)
                        {
                            // data is smaller; completed reading so, end
                            break;
                        }
                    }
                    imageData=imagememoryStream.ToArray();
                }
                return imageData;
            }
            catch( Exception exception )
            {
                throw new DataException( exception.StackTrace );
            }

3
你能否不把这些数据分成块?为什么要这么大? - Simon Whitehead
你能发布你的代码吗? - Ajay
“我说先生,你的进程似乎……内存不足了。真是非常奇怪!”从未有理解32位进程可访问多少地址空间的程序员会这样说。 - ta.speot.is
尝试在循环内调用GC.Collect(); - kol
我在循环内使用了GC.Collect(),但是仍然出现了相同的问题...有其他替代方法吗? - mottukutty
可能是重复的问题,参考链接:https://dev59.com/u3M_5IYBdhLWcg3w9oMA - Ankush Madankar
1个回答

3

由于可用连续(而非总共)内存不足,MemoryStream经常会抛出OutOfMemoryExceptions。有许多替代实现可以减轻此问题。例如,请查看MemoryTributary

或者,根据您的需求,您可以尝试直接写入存储而不是内存。


它运行得很好。非常感谢您宝贵的建议。但是我在托管cpp中有一个依赖项目,它显示“没有足够的存储空间来处理此命令”异常。您能提供任何解决方案吗? - mottukutty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接