2016-03-22 4 views
0

BackgroundWorker.CancelAsync()が動作しない問題が発生しています。 WorkerSupportsCancellationをTRUEに設定しました。 DoWorkでBackgroundWorker1.CancellationPendingもポーリングしています。ここで私が達成しようとしているもののサンプルコードです。バックグラウンドワーカーは、タイムスタンプをループし、Measurement変数に値を割り当てています。私は最後に報告された測定変数を照会し、リストボックスに書き込むサブルーチンを持っています。 5回のループの後、私はBackgroundWorker.CancelAsync()を送ります。キャンセルが保留中であることがわかりますが、実際にバックグラウンドワーカーをキャンセルするわけではありません。これは競争状態ですか?vb.netバックグラウンドワーカーが動作しない

Public Class Form1 

Dim Measurement As String 
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 

    BackgroundWorker1.RunWorkerAsync() 
    Delay(0.5) 

    For x = 1 To 5 
     ListBox1.Items.Add(Measurement) 
     ListBox1.TopIndex = ListBox1.Items.Count - 1 
     TextBox1.Text = BackgroundWorker1.CancellationPending 
     Delay(1) 
    Next 

    BackgroundWorker1.CancelAsync() 

    TextBox1.Text = BackgroundWorker1.CancellationPending 
    ListBox1.Items.Add("Cancel Pend: " & BackgroundWorker1.CancellationPending) 
    Delay(5) 
    ListBox1.Items.Add("Busy: " & BackgroundWorker1.IsBusy) 

End Sub 

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 

    If BackgroundWorker1.CancellationPending = True Then 
     e.Cancel = True 
     BackgroundWorker1.Dispose() 
     Exit Sub 
    Else 
     Do 
      Measurement = Now() 
     Loop 
    End If 

End Sub 

エンドクラス

+2

ループ内のキャンセルの確認を移動(またはコピー)します – Steve

+0

うわー...私はそれを逃したとは信じられません...スティーブありがとう! – HurstOlds

+0

@HurstOldsもう一度ボタンをクリックするとどうなりますか? 'BackgroundWorker1.Dispose()'がその場所にある場合...私は何が起こるか知っています:) – Codexer

答えて

1

あなただけドゥ内部の取り消しのチェックを移動する必要があります...ループ、それ以外の場合は唯一のDoWorkイベントハンドラの開始時にテストされ、決してその

後になります
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 

    If BackgroundWorker1.CancellationPending = True Then 
     e.Cancel = True 
     BackgroundWorker1.Dispose() 
    Else 
     Do 
      If BackgroundWorker1.CancellationPending = True Then 
      e.Cancel = True 
      BackgroundWorker1.Dispose() 
      Exit Do 
      Else 
      Measurement = Now() 
      End If 
     Loop 
    End if 
End Sub 
関連する問題