我实现了这样的进度条:
TableCreation.ProgressBar2.Value = 0
TableCreation.ProgressBar2.Maximum = CInt(FieldsNumber)
'==================
For SecondLoopCount = 1 To CInt(FieldsNumber) Step 1
'----------------------------------------------
TableCreation.ProgressBar2.Value = SecondLoopCount
TableCreation.ProgressBar2.Refresh()
TableCreation.ProgressBar2.Show()
' ....... Some Code ......
Next
我在此子句中处理BackgroundWorker
的{{1}}事件:
DoWork
但是当我这样做时:
Public Shared Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim bw As BackgroundWorker = New BackgroundWorker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
For i = 1 To 10
If worker.CancellationPending = True Then
e.Cancel = True
Exit For
Else
' Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500)
worker.ReportProgress(i * 10)
End If
Next
End Sub
如果Dim e1 As System.ComponentModel.DoWorkEventArgs
TableCreation.ProgressBar2.Value = SecondLoopCount
TableCreation.ProgressBar2.Refresh()
TableCreation.ProgressBar2.Show()
bw_DoWork(sender, e1)
是一个Object,则会抛出错误:
无法将类型为'e_store.TableCreation'的对象强制转换为'System.ComponentModel.BackgroundWorker'。
sender
只是我项目中的一个表单。
答案 0 :(得分:6)
您不应该直接致电bw_DoWork()
。这就是错误发生的地方,您在当前上下文(表单)中发送sender
对象,然后尝试将其转换为BackgroundWorker
。
您应该将处理程序添加到DoWork
Sub,
Public Shared Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
然后,不要直接致电bw_DoWork()
,而是bw.RunWorkerAsync()
。然后,这将引发DoWork
事件并调用该方法。然后,您的sender
将成为BackgroundWorker。