c# – 使用GC.AddMemoryPressure()防止OutOfMemoryException?
我正在除錯一個方法,我們用於在將影象顯示在我們的系統中之前用特定的文字標記影象.
標籤方法現在看起來像這樣:
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()可以從服務中獲取影象的全部操作 – >儲存 – >標籤是相當大的一個,所以收集的效能將是最小的,但我真的想要一個更好的解決方案.
如果有人有一個聰明的解決方案,請分享.