mercredi 8 novembre 2023

System.OutOfMemoryException .NET 4.8 WPF App

I'm working on a WPF (WCF architecture) app. This app has 2 main solutions, the client(front end) and the controller(back end), the way the client communicates with the back end is through reflective calls, in essences it builds up a XML doc containing info like the method to execute, the namespace that the method is in and method args etc...

So this specific method is to upload documents. It works perfectly until the file is > 1GB in size. The error occurs when the client builds up the XML doc for the reflective call.

We add to the XML doc like this:

result.Add(new XElement(itemProperty.Name, new XCData(data)));

In this case the itemProperty.Name is the method name and the XCData is the method args. So the doc to upload will obvisolsy be the arguments, we receive it in a byte[]. And we need to pass it to the XCData constructor as a string, so the following is used:

string data= Convert.ToBase64String((byte[])value)

Note that this works with smaller files but with the 1GB file a 'System.OutOfMemoryException' exception is thrown when trying to convert the byte[] to base64String.

I have tried reading the array in chunks, but when calling the stringBuilder.ToString(), the same exception is thrown...

 public static string HandleBigByteArray(byte[] arr)
        {
            try
            {
                
                #region approach 2
                int chunkSize = 104857600;//100MB
                StringBuilder b64StringBuilder = new StringBuilder();
                int offset = 0;

                while (offset < arr.Length)
                {
                    int remainingBytes = arr.Length - offset;
                    int bytesToEncode = Math.Min(chunkSize, remainingBytes);
                    string base64Chunk = Convert.ToBase64String(arr, offset, bytesToEncode);
                    b64StringBuilder.Append(base64Chunk);
                    offset += bytesToEncode;
                }


                return b64StringBuilder.ToString();
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }

I have no idea what to do or how to further debug/approach this..





Aucun commentaire:

Enregistrer un commentaire