mottukutty
mottukutty

Reputation: 687

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 );
            }

Upvotes: 3

Views: 8338

Answers (1)

Nigel Whatling
Nigel Whatling

Reputation: 2391

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.

Upvotes: 3

Related Questions