Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Loop through multiple images to convert to base64 to Http POST - Garbage Collection

ledragonledragon Member ✭✭✭
edited September 2019 in Xamarin.Forms


My app needs to loop though potentially a large number of images for upload, during which I convert to Base64 using the following code:

            using (var stream = File.OpenRead(filePath))
                var bytes = new byte[stream.Length];
                await stream.ReadAsync(bytes, 0, (int)stream.Length);

                var base64Image = Convert.ToBase64String(bytes);

                int base64EncodedSize = 4 * bytes.Length / 3;
                var sizeInKb = base64EncodedSize / 1000;

                Debug.Write($"OPOCDebug {DateTime.Now.ToString("hh:mm:ss.fff")}: ConvertImageAsync FilePath String Length {sizeInKb}Kb");

                return base64Image;
        catch (Exception ex)
            throw ex;

The above is called via a foreach loop on the Image collection and I'm seeing lots of the following in the Debug window which is slowing down the overall process:

09-24 09:52:03.544 I/.telerik.OPOCv(28042): Explicit concurrent copying GC freed 5(79KB) AllocSpace objects, 0(0B) LOS objects, 64% free, 3MB/9MB, paused 192us total 29.213ms

I've read the following post:

...which states: "Every garbage collection (explicit or not) has performance implications, because it blocks all the threads until finished." Can any one suggest how I refactor the above to prevent the need for GC or any alternative on how to perform the requirements?

Thanks in advance.


  • ledragonledragon Member ✭✭✭

    Attached is Debug output with some logging

  • JohnHardmanJohnHardman GBUniversity admin


    You are likely using and fragmenting the Large Object Heap as a result of working with a large number of images. Doing that is indeed likely to cause GC performance problems.

    I highly recommend the book "Writing High-Performance .Net Code" by Ben Watson (2nd edition), which has the best coverage of garbage collection and approaches for minimising GC issues that I have read. (I am not connected with the author or publisher in any way)

  • ledragonledragon Member ✭✭✭

    Hmm really struggling with this. @JohnHardman Yes you are right I am sure, but nothing I try seems to make a difference.

Sign In or Register to comment.