0

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);
Stalfos
  • 1,348
  • 2
  • 9
  • 12
  • 1) Are you running on 32 bit or 64 bit? See [How to determine programmatically whether a particular process is 32-bit or 64-bit](https://stackoverflow.com/questions/1953377) if you're not sure. 2) What is the complete traceback and message of the out of memory exception? – dbc Feb 28 '16 at 17:49
  • Looks like I am running this in 32 bit based on your link. Unfortunately I have not documented the traceback and unfortunately with my second implementation it has occurred VERY rarely (only 3 times so far) so I do not have a reliable way of replicating this :/ – Stalfos Feb 28 '16 at 18:00
  • Then I suggest switching to 64 bit. You may be running 32 bit inadvertently since "Prefer 32 bit" became the default. See http://blogs.microsoft.co.il/sasha/2012/04/04/what-anycpu-really-means-as-of-net-45-and-visual-studio-11/ – dbc Feb 28 '16 at 18:09
  • 1) Are you serializing manually because `JsonResult` uses `JavaScriptSerializer`? 2) Have you enabled dynamic compression? See http://stackoverflow.com/questions/2138243/how-do-i-compress-a-json-result-from-asp-net-mvc-with-iis-7-5 – dbc Feb 28 '16 at 18:11
  • Also, I suggest trying `JsonStreamingResult` from [Streaming large list of data as JSON format using Json.net](https://stackoverflow.com/questions/26269438/streaming-large-list-of-data-as-json-format-using-json-net). – dbc Feb 28 '16 at 18:23
  • Thanks, I'll look at these solutions. I just changed the project to build and run under x64, let's see how this goes – Stalfos Feb 28 '16 at 19:04

0 Answers0