簡體   English   中英

C#System.OutOfMemoryException未處理

[英]C# System.OutOfMemoryException was unhandled

我使用foreach從文件夾中讀取所有圖像

        string[] filePaths = Directory.GetFiles(Workspace.InputFolder, "*.*");
        foreach (string imageFile in filePaths)
        {
            // Some Process here, the output are correct, just after output 
               the error happen
        }

但是出來錯誤

System.OutOfMemoryException was unhandled
  Message=Out of memory.
  Source=System.Drawing 

問題是由foreach循環導致的,在過程完成后繼續循環嗎? 我應該怎么做才能釋放內存? 謝謝。

考慮到您的異常,您似乎正在使用System.Drawing命名空間中的對象。

例如,如果要在foreach循環中打開和操作圖像,請確保在Dispose()完圖像資源后立即調用Dispose()釋放圖像資源。 您也可以將其包裝在using語句中,即:

    foreach (string imageFile in filePaths)
    {
        using (var image = Image.FromFile(imageFile)
        {
            // Use the image...
        } // Image will get disposed correctly here, now.
    }

請注意,問題可能不僅是圖像,還包括實現IDisposable任何資源。 System.Drawing中的許多類都是可拋棄的-確保您按上述方式(通過使用)訪問它們,或在完成后對其調用Dispose()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM