在VB.Net中,我创建了一个似乎有用的后台工作程序。它设置如下:
Private bw As BackgroundWorker = New BackgroundWorker
Public Sub construct_configure()
bw.WorkerReportsProgress = True
bw.WorkerSupportsCancellation = True
AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
end sub
然后我将doWork Sub设置为:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
' create the picture box
pic_holder = New PictureBox()
' Show GIF and disable whatever you need to
With pic_holder
.Image = My.Resources.counter_gif
.Size = New Size(200, 100)
.Location = New Point(0, 0)
.Visible = True
.BackColor = Color.Red
End With
Main.Controls.Add(pic_holder)
pic_holder.BringToFront()
MessageBox.Show("worker started")
End Sub
当我点击我的按钮来调用Sub时,会显示消息框,但动画gif从不这样做。我试图简单地设置一个指标,表明有一些背景工作正在进行中。当我在父子中设置它时,gif会出现。
另外,我想将gif放在已经存在的面板中,但每次尝试时,都会出现一个交叉线程错误,表明该面板是在另一个线程中创建的。我怎么能解决这个问题?
感谢。
答案 0 :(得分:1)
如果要调用主表单,建议您在 ProgressChanged 事件中执行此操作。 bw_ProgressChanged在与主窗体相同的线程上调用。
Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bw.DoWork
'WORKER THREAD, do not invoke main form.
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
'Report start
worker.ReportProgress(0)
'Do some work...
Threading.Thread.Sleep(5000)
'Report end.
worker.ReportProgress(100)
End Sub
Private Sub bw_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles bw.ProgressChanged
'MAIN THREAD, safe to invoke main form.
If (e.ProgressPercentage = 0) Then
'Started: Do something...
ElseIf (e.ProgressPercentage = 100) Then
'Stopped: Do something...
End If
End Sub