Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception of type 'System.OutOfMemoryException' was thrown. C# when using Memory stream

I am working with wpf application and memory stream write method is used in that to write dicom data bytes.It shows the Exception of type System.OutOfMemoryException when try to write big dicom data having size more than 70 mb. Can you please suggest any solution to resolve this.

The piece of code is like this

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 );
            }
like image 780
mottukutty Avatar asked Mar 18 '26 02:03

mottukutty


1 Answers

It is quite common for MemoryStream to throw OutOfMemoryExceptions due to lack of contiguous (not total) memory available. There are a number of alternate implementations that lessen this problem. Take a look at MemoryTributary for example.

Or, depending on your needs, you could try writing direct to storage instead of memory.

like image 91
Nigel Whatling Avatar answered Mar 20 '26 14:03

Nigel Whatling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!