在 ASP.NET 中创建巨大字符串时出现 OutOfMemoryException

发布于 2024-09-19 21:11:07 字数 2083 浏览 6 评论 0原文

将大量数据导出到字符串(csv 格式)时,出现 OutOfMemoryException。解决这个问题的最佳方法是什么?该字符串将返回到 Flex 应用程序。

我要做的是将 csv 导出到服务器磁盘并返回一个 URL 给 Flex。像这样,我可以刷新写入磁盘的流。

更新:

字符串是用 StringBuilder 构建的:

StringBuilder stringbuilder = new StringBuilder();
string delimiter = ";";
bool showUserData = true;

// Get the data from the sessionwarehouse
List<DwhSessionDto> collection 
     =_dwhSessionRepository.GetByTreeStructureId(treeStructureId);

// ADD THE HEADERS
stringbuilder.Append("UserId" + delimiter);
if (showUserData)
{
    stringbuilder.Append("FirstName" + delimiter);
    stringbuilder.Append("LastName" + delimiter);
}
stringbuilder.Append("SessionId" + delimiter);
stringbuilder.Append("TreeStructureId" + delimiter);
stringbuilder.Append("Name" + delimiter);
stringbuilder.Append("Score" + delimiter);
stringbuilder.Append("MaximumScore" + delimiter);
stringbuilder.Append("MinimumScore" + delimiter);
stringbuilder.Append("ReducedScore" + delimiter);
stringbuilder.Append("ReducedMaximumScore" + delimiter);
stringbuilder.Append("Duration" + delimiter);
stringbuilder.AppendLine("Category" + delimiter);

foreach (var dwhSessionDto in collection)
{
    stringbuilder.Append(
        getPackageItemsInCsvFromDwhSessionDto(
            dwhSessionDto, delimiter, showUserData));
}

return stringbuilder.ToString();

字符串被发送回 Flex,如下所示:

var contentType = "text/csv";
string result = exportSessionService.ExportPackage(treeStructureId);
// Write the export to the response
_context.Response.ContentType = contentType;
_context.Response.AddHeader("content-disposition", 
    String.Format("attachment; filename={0}", treeStructureId + ".csv"));

// do not Omit the Vary star so the caching at the client side will be disabled
_context.Response.Cache.SetOmitVaryStar(false);
_context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

if (!String.IsNullOrEmpty(result))
{
    _context.Response.Output.Write(result);
    _context.Response.Output.Close();
}
else
{
    _context.Response.Output.Write("No logs");
}

When exporting a lot of data to a string (csv format), I get a OutOfMemoryException. What's the best way to tackle this? The string is returned to a Flex Application.

What I'd do is export the csv to the server disk and give back an url to Flex. Like this, I can flush the stream writing to the disk.

Update:

String is build with a StringBuilder:

StringBuilder stringbuilder = new StringBuilder();
string delimiter = ";";
bool showUserData = true;

// Get the data from the sessionwarehouse
List<DwhSessionDto> collection 
     =_dwhSessionRepository.GetByTreeStructureId(treeStructureId);

// ADD THE HEADERS
stringbuilder.Append("UserId" + delimiter);
if (showUserData)
{
    stringbuilder.Append("FirstName" + delimiter);
    stringbuilder.Append("LastName" + delimiter);
}
stringbuilder.Append("SessionId" + delimiter);
stringbuilder.Append("TreeStructureId" + delimiter);
stringbuilder.Append("Name" + delimiter);
stringbuilder.Append("Score" + delimiter);
stringbuilder.Append("MaximumScore" + delimiter);
stringbuilder.Append("MinimumScore" + delimiter);
stringbuilder.Append("ReducedScore" + delimiter);
stringbuilder.Append("ReducedMaximumScore" + delimiter);
stringbuilder.Append("Duration" + delimiter);
stringbuilder.AppendLine("Category" + delimiter);

foreach (var dwhSessionDto in collection)
{
    stringbuilder.Append(
        getPackageItemsInCsvFromDwhSessionDto(
            dwhSessionDto, delimiter, showUserData));
}

return stringbuilder.ToString();

The string is sent back to Flex like this:

var contentType = "text/csv";
string result = exportSessionService.ExportPackage(treeStructureId);
// Write the export to the response
_context.Response.ContentType = contentType;
_context.Response.AddHeader("content-disposition", 
    String.Format("attachment; filename={0}", treeStructureId + ".csv"));

// do not Omit the Vary star so the caching at the client side will be disabled
_context.Response.Cache.SetOmitVaryStar(false);
_context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

if (!String.IsNullOrEmpty(result))
{
    _context.Response.Output.Write(result);
    _context.Response.Output.Close();
}
else
{
    _context.Response.Output.Write("No logs");
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

谜泪 2024-09-26 21:11:13

对我来说,最好创建一个通用处理程序页面(ashx),并将所有数据直接发送到 flex。

直接到流...

这里有 关于这个问题的好文章

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

压抑⊿情绪 2024-09-26 21:11:13

首先,增加 RAM 需要多少钱?如今,硬件比程序员便宜。

没有更多的内容可以继续,更具体的建议是有点技巧的。但您希望避免实际将 CSV 构建为字符串,而是将其从数据源流式传输到磁盘,而不是将整个内容保存在内存中。

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.

生生不灭 2024-09-26 21:11:12

字符串是使用 StringBuilder 创建的,并使用 HttpContext.Reponse.Output.Write(result) 传回 Flex 应用程序; ——列文·卡登

那么你基本上要做的是:

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

对吗?这可能不是您的确切代码,但听起来是一个很好的近似值。

那么解决方案很简单:

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

流式传输通常比缓冲整个内容并将其作为一个整体发送出去更好。

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.

紫罗兰の梦幻 2024-09-26 21:11:12

我要做的是将 csv 导出到服务器磁盘

听起来是正确的想法。但是您是否首先创建完整字符串?如果你逐行编写,你不应该得到OOM

编辑,在看到代码后

你只使用StringBuilder.Append(x),所以你可以稍微重构你的代码,用替换它>_context.Response.Output.Write(x)。这可能会牺牲一点你们的分离,但这是有充分理由的。

如果您想继续使用 StringBuilder,如果您可以估计结果大小,将会有很大帮助。添加足够的余量并使用

   StringBuilder stringbuilder = new StringBuilder(estimate);

这可以节省 StringBuilder 的增长(复制),并减少 LOH 上的内存使用和碎片。

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.

著墨染雨君画夕 2024-09-26 21:11:11

您的 CSV 字符串增长到超过 80000 字节并最终位于 LargeObjectHeap 上。 LOH 的垃圾收集方式与其他代不同,并且会随着时间的推移而产生碎片,例如在向服务器发出多次请求之后或者如果您使用字符串连接(顽皮!)来构建此 csv 数据。结果是您的程序保留的内存比实际使用的内存多得多,并且抛出 OutOfMemory 异常。

这种情况下的修复方法是将 csv 数据直接写入响应流,而不是字符串变量甚至 StringBuilder。这不仅可以避免大型对象堆,而且可以降低整体内存使用量,并更快地将数据推送给用户。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文