PictureBox停止添加图像

时间:2016-11-15 03:19:16

标签: vb.net image backgroundworker picturebox

我正在使用工作线程将.png图像(从路径字符串)加载到全局PictureBox2对象中,然后退出_RunWorkerCompleted以使用PictureBox2的宽度和高度来处理名为processpic2的方法中的其他工作。一切正常,直到大约第5或第6张图像被添加到PB。在这一点上,在processpic2方法中,抛出异常,因为PictureBox2的image属性的计算结果为空。

为什么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

2 个答案:

答案 0 :(得分:1)

BackgroundWorker的重点是做背景工作。对UI进行更改与后台工作完全相反。这是前台工作。如果您的任务是清除PictureBox的当前内容,从文件加载图像然后显示该图像,则只有中间步骤是后台工作,因此只应在{{1}中完成中间步骤事件处理程序。第一步应该在调用DoWork之前完成,最后一步应该在RunWorkerAsync事件处理程序中完成。

说了这么多,在这种情况下为什么要使用RunWorkerCompleted?为什么不简单地调用BackgroundWorker本身的LoadAsync方法?

答案 1 :(得分:0)

解决方案 - 感谢收到的建议以及我在MSDN上发现的有关LoadAsync PictureBox PictureBox2.Image = Nothing PictureBox2.WaitOnLoad = False ' Load the image asynchronously. PictureBox2.LoadAsync(pathstr) 方法的内容,以下代码解决了该问题:

ij