2010/01/15(Fri) 20:00:29 編集(投稿者)
なぜわざわざ別クラス作成して複雑なコードを組んでいるのかがようわからん。
とりあえず、そのままの状態でやるとするなら
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles ackgroundWorker1.DoWork
Dim bgw As BackgroundWorker = CType(sender, BackgroundWorker)
Dim hoge As New hoge(Me)
hoge.DisplayMessage(bgw, e)
End Sub
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Me.BackgroundWorker1.CancelAsync()
While Me.BackgroundWorker1.IsBusy
Application.DoEvents()
End While
End Sub
' hogeクラス
Public Sub DisplayMessage(ByVal bgw As BackgroundWorker, ByVal e As DoWorkEventArgs)
Dim label As New Form1.Label1ValueDelegate(AddressOf _form.Label1_Value)
For i As Integer = 100 To 1 Step -1
If bgw.CancellationPending Then
e.Cancel = True
Return
End If
label.Invoke(i.ToString)
System.Threading.Thread.Sleep(100)
Next
End Sub
とすればできる。
でもわざわざこんな複雑なコードを書かなくてもProgressChangeイベント関数はフォームスレッドで実行されるから
直接コントロールを扱えるから以下のコードで済む
(BackgroundWorkerのWorkeReportsProgress及びWorkerSupportsCancellationをTrueに設定しておく)
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim bgw As BackgroundWorker = CType(sender, BackgroundWorker)
For i As Integer = 100 To 1 Step -1
If bgw.CancellationPending Then
e.Cancel = True
Return
End If
bgw.ReportProgress(i)
System.Threading.Thread.Sleep(100)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Label1.Text = e.ProgressPercentage.ToString()
End Sub