3

I have 8 large blocks of memory (28mb each). They are stored in unmanaged (native) code. And I want to dump them into files. But after I dump them, they are not released and I have 230mb busy memory, which make not available to continue running my app. Further thrown OutOfMemory. Here my dumping code:

//* Dump input images
for (int i = 0; i < frames.Length; i++)
{
    StorageFile file = await localFolder.CreateFileAsync(
        string.Format("FRAME_{0}.yuv", i), 

    CreationCollisionOption.ReplaceExisting);

    using (var stream = await file.OpenStreamForWriteAsync())
    {
        byte[] image = SwapHeap.copyFromHeap(frames[i].ImagePtr, (int)frames[i].Width * (int)frames[i].Height * 3 / 2);
        await stream.WriteAsync(image, 0, image.Length);
        await stream.FlushAsync();
        image = null;
    }
}
...
System.GC.Collect();

And native code to get byte[] from int pointer:

Array<uint8>^ SwapHeap::copyFromHeap(const int ptr, int length) 
{
    Array<uint8>^ res = ref new Array<uint8>(length);
    memcpy(res->Data, (byte*)ptr, length);
    return res;
}

I free memory in native code using free((byte*)ptr); and it's ok. But I can't understand, why byte arrays are not released?

P.S. I can dump data using native code, but I want to understand how GC works (msdn I've already read).

Romasz
  • 29,662
  • 13
  • 79
  • 154
Maxim Metelskiy
  • 1,389
  • 14
  • 29

1 Answers1

0

Looks like problem in Stream class. As far as I can understood from different tests, it locks byte array, which is written to stream. And it's not closed or released outside using block. If use FileIO instead of Stream and change dumping code to:

// Dump input images
for (int i = 0; i < frames.Length; i++)
{
    StorageFile file = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(
        string.Format("FRAME_{0}.yuv", i), CreationCollisionOption.ReplaceExisting);

    byte[] image = SwapHeap.copyFromHeap(frames[i].ImagePtr, (int)frames[i].Width * (int)frames[i].Height * 3 / 2);
    await FileIO.WriteBytesAsync(file, image);
    image = null;
    file = null;
}

Everything is fine.

Maxim Metelskiy
  • 1,389
  • 14
  • 29