2016-09-11 74 views
1

我正在編寫一個播放幻燈片(除其他外)的程序。幻燈片由backgroundWorker控制,並設置爲while(true)循環,因此它會不斷播放圖像。我的問題是我不知道如何處理舊圖像,以便它們不佔用內存(稍後,程序會拋出「內存不足異常」)。如果我調用horPicBox.Image.Dispose(),那麼它在這之後不會讓我使用pictureBox處理一個pictureBox圖像而不會丟失圖片盒

有沒有辦法從內存中釋放舊圖像?如果我看看VS中的診斷工具,每次圖像更改時內存都會上升。 .. enter image description here

注:ImagePaths是文件路徑爲幻燈片圖像列表

這是BackgroundWorker的運行代碼:

private void PlayImages() 
    { 
     Random r = new Random(); 
     int index; 
     Stopwatch watch = new Stopwatch(); 

     while (true) 
     { 
      index = r.Next(imagePaths.Count); 
      horPicBox.Image = Image.FromFile(imagePaths[index]); 

      watch.Start(); 

      while (watch.ElapsedMilliseconds < 5000) 
      { 

      } 

      watch.Stop(); 
      watch.Reset(); 

      //picWorker.ReportProgress(0); 
     } 
    } 

我可以向UI線程報告progressChanged,但我不知道我需要從UI線程(如果有的話)中釋放舊圖像。提前致謝!!

+0

*如果我叫horPicBox.Image.Dispose(),那麼它不會讓我用圖片框在所有後*什麼,這對誰發送一個保鏢如果你嘗試了,你會覺得粗糙嗎? – Will

回答

3

圖像數量和總大小是多少?我認爲最好加載陣列中的所有圖像,並將它們分配給horPicBox,而不是多次加載它們。要使用Dispose先分配horPicBox.Image到臨時對象,然後分配horPicBox.Imagenull或下一張圖像,並在年底的臨時對象調用Dispose

Image img = horPicBox.Image; 
horPicBox.Image = Image.FromFile(imagePaths[index]); 
if (img != null) img.Dispose(); 
+0

感謝您的回答。有數百個圖像,所以如果我預先加載它們,它會產生內存異常 – BrianH

4

如果你的圖像存儲到該類型的變量,然後設置您的圖片框圖像,然後處置舊的一個像

 Image oldImage = horPicBox.Image; 
     horPicBox.Image = Image.FromFile(imagePaths[index]); 
     oldImage.Dispose(); 
+0

這很奇妙!非常感謝! (自i486先說,我會給他們答案) – BrianH

相關問題