I am building a web application with MVC. For one of my views I need to fetch a large string and then bind it to jsTree. However, several times I am receiving the OutOfMemory exception. The string that is returned is with a length of 55,582,723 characters. I am dynamically creating a JArray with JObjects within the JArray.
Here is how I originally had it
var jArray = GetJArray();
return jArray.ToString();
With that code I received the exception very frequently. I then did some research and found out that I can write to a stream and then return the stream. So I changed the method to this:
var jArray = GetJArray();
var serializer = new JsonSerializer();
var ms = new MemoryStream();
var sw = new StreamWriter();
var writer = new JsonTextWriter(sw);
serializer.Serialize(writer, jArray);
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(ms, "text/plain");
Now with this code, it has improved a lot, however, I am still in some cases getting an OutOfMemory exception. The string that is returned will always be the same length as mentioned above.
Any insight to this will be much appreciated.
EDIT: To add a little more information the exception happened in my original implementation at:
return jArray.ToString();
The exception occurs in the my second implementation at:
serializer.Serialize(writer, jArray);