0

I am making a scanning component, but when I set a high resolution for the document (600 dpi), I tend to get System.OutOfMemoryException after just 1 or 2 scans.

My code is as follows

public ScannedImage SaveScannedImage(DataTransferredEventArgs e)
{
    if (e == null) throw new IOException();

    BitmapSource fullResImage;
    using (var fullResImageStream = e.GetNativeImageStream())
    {
        fullResImage = fullResImageStream.ConvertToWpfBitmap(e.ImageInfo.ImageWidth, e.ImageInfo.ImageLength);
    }

    BitmapSource lowResImage;
    using (var lowResImageStream = e.GetNativeImageStream())
    {
        lowResImage = lowResImageStream.ConvertToWpfBitmap(800, 0);
    }

    return new ScannedImage(lowResImage, fullResImage);
}

It is usually happening at the

using (var lowResImageStream = e.GetNativeImageStream())

Help would be much appreciated.

  • As you are dealing with Stream, use should use `GC.Collect()` method to collect the unmanaged resource when it is not required. – Manprit Singh Sahota Aug 02 '17 at 08:00
  • Are you sure `ImageLength` is what you want, and not e.g. `ImageHeight`? And what is `DataTransferredEventArgs`, `ConvertToWpfBitmap` etc.? – Luaan Aug 02 '17 at 08:00
  • @ManpritSinghSahota `GC.Collect()` *should* be called when it sees its out of memory, when it's still out of memory after that it will throw. But it's true that `GC.Collect()` will sometimes fix problems even though it shouldnt – EpicKip Aug 02 '17 at 08:02
  • I am using the Twain API. DataTransferredEventArgs contains event data from the scanner, and ConvertToWpfBitmap is a built-in BitmapSource method that converts the incoming System.IO.Stream to a displayable WPF image. – Aksel Vincent Berg Aug 02 '17 at 08:38

1 Answers1

0

What you see may be caused by large object heap (LOH) fragmentation.

That is hard to avoid, but you can compact the LOH explicitely.

GCSettings.LargeObjectHeapCompactionMode = 
    GCLargeObjectHeapCompactionMode.CompactOnce;

GC.Collect();

Also, make sure you run as a 64 bit process. Turn of the "Prefer 32 bit" option if it is on.

For more information, you might want to read

Kris Vandermotten
  • 10,111
  • 38
  • 49