OutOfMemoryException when creating huge string in ASP.NET

送分小仙女□ 提交于 2019-12-06 07:43:50

String is created with a StringBuilder and communicated back to Flex Application with HttpContext.Reponse.Output.Write(result); – Lieven Cardoen

So what you're basically doing is this:

StringBuilder str = new StringBuilder();
while(whatever)
{
    str.Append(thisNextLineIGuess);
}
Response.Output.Write(str.ToString());

Correct? That may not be your exact code, but it sounds like a good approximation.

Then the solution is simple:

while(whatever)
{
    Response.Output.Write(thisNextLineIGuess);
}

Streaming is usually better than buffering the whole thing and sending it out as a lump.

Your CSV strings are growing to over 80000 bytes and ending up on the LargeObjectHeap. The LOH is not garbage collected in the same way as other generations and can fragment over time, such as after many requests to your server or if you use string concatenation (naughty!) to build this csv data. The result is that your program reserves much more memory than it's actually using and an OutOfMemory exception is thrown.

The fix in this instance is to write your csv data directly to the Response stream rather than string variables or even StringBuilder. Not only will this avoid the Large Object Heap, but it will keep your overall memory use lower and start pushing data out to your user faster.

What I'd do is export the csv to the server disk

Sounds like the right idea. But are you creating the complete string first? If you write line by line you shouldn't get OOM

Edit, after seeing the code

You are only using StringBuilder.Append(x), so you can restructure your code a little to replace that with _context.Response.Output.Write(x). That might sacrifice a little bit of your separation but it's for a good cause.

And if you want to keep using a StringBuilder, it would help a lot if you could estimate the resulting size. Add a generous margin and use

   StringBuilder stringbuilder = new StringBuilder(estimate);

This saves on growing (copying) of the StringBuilder and reduces both memory use and fragmentation on the LOH.

For me its better to create a generic handler page (ashx), and send all your data directly to flex.

Direct to the stream...

Here are a nice article about this issue

First, how much would more RAM cost? These days hardware is cheaper than programmers.

Without a bit more to go on, more concrete recommendations are a bit of a trick. But you want to avoid actually building the CSV as a string but rather stream it from the data source to disk and not hold the entire thing in memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!