Forum Xamarin.Mac


The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to stop memory usage building up when opening files?

MattTapperMattTapper GBMember

We have a problem with memory usage when opening lots of filestream objects. We use a file cache to store information about images rather than having to load the full image each time when we only want to know thing like the size etc. But opening these cache file appears to be causing memory to be used up rapidly on the Mac.

The code to read the files is:

private async Task<Stream> ReadCacheFileAsync(string fileLocation, CancellationToken cancelToken)`
        using (var s = new FileStream(fileLocation, FileMode.Open, FileAccess.Read, FileShare.Read, 2097152, FileOptions.Asynchronous))
            var ms = new MemoryStream();

            await s.CopyToAsync(ms, 2097152, cancelToken);
            ms.Position = 0;

            return ms;
    catch (Exception ex)
        throw new ImageNotFoundException(fileLocation, "An error occured whilst trying to read the file", ex);

There is a similar function to write the files when needed. When our system needs create and read this cache for a new batch of images there is a rapid build up of memory usage. I've run the code through the Xamarin Profiler and it says the memory is being used up by the byte[] created by the filestream constructor. The last run had 15000 byte[] allocations using up 1.5Gb of memory. The vast majority of the allocations were the 2Mb buffers requested by the code above with nothing bigger than them.

But as you can see it's in a using statement so I don't understand why the memory is not being released. We run exactly the same code on Windows with no problems.



  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    Hmm, I'm somewhat surprised you are seeing different IO/memory behavior between macOS and Windows here.

    It looks like you should be able to isolate this to a trivial console application. Consider filing this as a runtime bug and seeing if they can help you.

Sign In or Register to comment.