2016-11-15 154 views
0

我正在使用工作線程將.png圖像(從路徑字符串)加載到全局PictureBox2對象中,然後退出_RunWorkerCompleted以在名爲processpic2的方法中使用PictureBox2的寬度和高度進行其他工作。一切正常,直到第5或第6張圖像被添加到PB。這一點,在processpic2方法中,由於PictureBox2的圖像屬性評估爲無,所以拋出異常。PictureBox停止添加圖像

爲什麼PB會在一段時間後停止拍照?

Public Class Form1 
Public WithEvents BackgroundWorker1 As New System.ComponentModel.BackgroundWorker 

Private Sub BackGroundworker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
    Dim args As ArgumentType = e.Argument 
    PictureBox2.Image = Nothing 
    PictureBox2.Invalidate() 
    Dim img As Image 
    Using str As Stream = File.OpenRead(args._pathstr) 
     img = Image.FromStream(str) 
    End Using 
    PictureBox2.Image = img 
    e.Result = "done" 
End Sub 

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _Handles BackgroundWorker1.RunWorkerCompleted 
    'Called when the BackgroundWorker is completed. 
    processpic2() 
End Sub 

Sub btnLoadPicture(pathstr) 
    Dim args As ArgumentType = New ArgumentType() 
    args._pathstr = pathstr 
    BackgroundWorker1.RunWorkerAsync(args) 
End Sub 

Sub processpic2() 
    If PictureBox2.Image Is Nothing Then MsgBox("Image is Nothing") 
End Sub 
+1

不要從後臺工作進程的UI元素,這就是爲什麼...使用委託和調用...圖片框是在不同的線程比背景的工作人員... – Codexer

+0

我不認爲我需要回答這個爲什麼評論。看看你正在使用的UI控件的調用會讓你朝着正確的方向前進。如果您仍然需要幫助,請更新您的問題,我們很樂意爲您提供幫助。 – Codexer

+1

我同意Zaggler。你可能會在'RunWorkerCompletedEventArgs'(即'e.Result')中返回加載的圖像,並在RunWorkerCompleted中設置'PictureBox.Image'。 – SSS

回答

1

BackgroundWorker整點要做後臺工作。對UI進行更改與後臺工作完全相反。這是前臺工作。如果您的任務是清除PictureBox的當前內容,請從文件加載圖像,然後顯示該圖像,但只有中間步驟是後臺工作,所以只有中間步驟應在DoWork事件處理程序中完成。第一步應在撥打RunWorkerAsync之前完成,最後一步應在RunWorkerCompleted事件處理程序中完成。

說了這麼多,在這種情況下爲什麼要使用BackgroundWorker?爲什麼不簡單地調用PictureBox本身的LoadAsync方法?

+0

謝謝 - 不知道'PictureBox'的'LoadAsync'方法,所以會研究。有一件事是肯定的,圖像大約是600 x 400像素的.png,即使設置了「PictureBox1.Image = Nothing」,圖片框在加載和查看大約5-8張圖像之後往往會掛起。似乎有些記憶內容正在被填滿或什麼東西。 'PictureBox1.Invalidate'和'PictureBox1.Image = Nothing'不能幫助消除這個特點。 – wrtsvkrfm

+0

'圖像'是一個可丟棄的物體。如果你正在創建一個Image對象並將它分配給一個PictureBox的Image屬性,那麼當你完成它時,你應該在該Image對象上調用Dispose。 – jmcilhinney

0

解決方案 - 得益於建議收到,而我在MSDN上找到有關的PictureBoxLoadAsync方法下面的代碼解決了這個問題:

PictureBox2.Image = Nothing 

PictureBox2.WaitOnLoad = False 

' Load the image asynchronously. 
PictureBox2.LoadAsync(pathstr)