c# – 使用GC.AddMemoryPressure()防止OutOfMemoryException?

栏目: C# · 发布时间: 5年前

内容简介:我正在调试一个方法,我们用于在将图像显示在我们的系统中之前用特定的文本标记图像.标签方法现在看起来像这样:将内容放在上下文中:在从图像服务器检索到图像并将其保存到本地缓存(我们的系统与需要相同图像的其他系统共享)之后,将调用此方法.

我正在调试一个方法,我们用于在将图像显示在我们的系统中之前用特定的文本标记图像.

标签方法现在看起来像这样:

private static Image TagAsProductImage(Image image)
{
    try
    {
        // Prepares the garbage collector for added memory pressure (500000 bytes is roughly 485 kilobytes).
        // Should solve some OutOfMemoryExceptions.
        GC.AddMemoryPressure(500000);

        using (Graphics graphics = Graphics.FromImage(image))
        {
            // Create font.
            Font drawFont = new Font("Tahoma", image.Width*IMAGE_TAG_SIZE_FACTOR);

            // Create brush.
            SolidBrush drawBrush = new SolidBrush(Color.Black);

            // Create rectangle for drawing.
            RectangleF drawRect = new RectangleF(0, image.Height - drawFont.GetHeight(), image.Width,
                                                    drawFont.GetHeight());

            // Set format of string to be right-aligned.
            StringFormat drawFormat = new StringFormat();
            drawFormat.Alignment = StringAlignment.Far;

            // Draw string to screen.
            graphics.DrawString(TAG_TEXT, drawFont, drawBrush, drawRect, drawFormat);
        }
    }
    // If an out of memory exception is thrown, return the unaltered image.
    catch(OutOfMemoryException)
    {
        GC.RemoveMemoryPressure(500000);
        return image;
    }

    GC.RemoveMemoryPressure(500000);
    return image;
}

将内容放在上下文中:在从图像服务器检索到图像并将其保存到本地缓存(我们的系统与需要相同图像的其他系统共享)之后,将调用此方法.

我们一直在使用OutOfMemoryExceptions时遇到问题(图形…(当图像需要在标记之前从服务器检索时,如果图像存在于缓存中,标记没有出现问题).

为了防止/规避OutOfMemoryException,我尝试了三种不同的方法,当他们工作时,我并不喜欢任何一种.

首先我尝试做一个通用的GC.Collect();之前调用Graphics.FromImage(image),当然这个功能,但是我不喜欢强制收集,因为它对性能有很大的打击.

我的第二种方法是在catch语句中调用GC.Collect(),然后递归调用TagAsProductImage(image),但如果GC无法释放足够的内存,这可能会导致无限循环.

最后我结束了上面的代码,我不能说我喜欢任何一个.

使用GC.Collect()可以从服务中获取图像的全部操作 – >保存 – >标签是相当大的一个,所以收集的性能将是最小的,但我真的想要一个更好的解决方案.

如果有人有一个聪明的解决方案,请分享.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Graph Theory

Introduction to Graph Theory

Douglas B. West / Prentice Hall / 2000-9-1 / USD 140.00

For undergraduate or graduate courses in Graph Theory in departments of mathematics or computer science. This text offers a comprehensive and coherent introduction to the fundamental topics of graph ......一起来看看 《Introduction to Graph Theory》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换