gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:07:08 24 4
gpt4 key购买 nike

我目前正在调试我们用来在系统中显示图像之前用特定文本标记图像的方法。

标签方法目前看起来像这样:

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;
}

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

当到达 using (Graphics... 时,我们遇到了 OutOfMemoryExceptions 问题(当需要在标记之前从服务器检索图像时,如果图片存在于缓存中标记一直不是问题)。

为了防止/规避 OutOfMemoryException,我尝试了三种不同的方法,虽然它们有效,但我并不真正喜欢它们中的任何一种。

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

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

最后我得到了上面的代码,我不能说我喜欢它。

我可能可以使用 GC.Collect(),因为从服务获取图像的整个操作 -> 保存 -> 标记是一个相当大的操作,因此性能受到影响collect 将是最小的,但我真的想要一个更好的解决方案。

如果有人对此有明智的解决方案,请分享。

最佳答案

如果您正在寻找一种方法来确保您有足够的内存可用于操作,请使用 MemoryFailPoint

有了这个,通过using,你可以定义一个你需要一定内存量的区域。如果不可用,它将抛出可恢复的 InsufficientMemoryException

参见 http://msdn.microsoft.com/en-us/library/system.runtime.memoryfailpoint.aspx获取更多信息。

关于c# - 使用 GC.AddMemoryPressure() 防止 OutOfMemoryException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com