BackgroundWorker.CancelAsync メソッド

定義

保留中のバックグラウンド操作のキャンセルを要求します。

public:
 void CancelAsync();
public void CancelAsync ();
member this.CancelAsync : unit -> unit
Public Sub CancelAsync ()

例外

次のコード例は、 メソッドを使用 CancelAsync して非同期 ("background") 操作を取り消す方法を示しています。 このコード例は、BackgroundWorker クラスのために提供されている大規模な例の一部です。

void cancelAsyncButton_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ )
{  
   // Cancel the asynchronous operation.
   this->backgroundWorker1->CancelAsync();
   
   // Disable the Cancel button.
   cancelAsyncButton->Enabled = false;
}
private void cancelAsyncButton_Click(System.Object sender, 
    System.EventArgs e)
{   
    // Cancel the asynchronous operation.
    this.backgroundWorker1.CancelAsync();

    // Disable the Cancel button.
    cancelAsyncButton.Enabled = false;
}
Private Sub cancelAsyncButton_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles cancelAsyncButton.Click
    
    ' Cancel the asynchronous operation.
    Me.backgroundWorker1.CancelAsync()

    ' Disable the Cancel button.
    cancelAsyncButton.Enabled = False
    
End Sub

注釈

CancelAsync 保留中のバックグラウンド操作を終了する要求を送信し、 プロパティを CancellationPendingtrue設定します。

を呼び出 CancelAsyncすと、ワーカー メソッドには実行を停止して終了する機会があります。 ワーカー コードでは、 プロパティが に設定されているかどうかを確認するために、 プロパティをCancellationPending定期的にチェックするtrue必要があります。

注意事項

イベント ハンドラーのコードは、取り消し要求が行われているのでDoWork作業を終了する可能性があり、ポーリング ループが にtrue設定されていない可能性があることにCancellationPending注意してください。 この場合、キャンセル要求がCancelled行われた場合でも、イベント ハンドラー内RunWorkerCompletedの の フラグSystem.ComponentModel.RunWorkerCompletedEventArgsは にtrue設定されません。 この状況は 競合状態 と呼ばれ、マルチスレッド プログラミングでは一般的な懸念事項です。 マルチスレッド設計の問題の詳細については、「 マネージド スレッドのベスト プラクティス」を参照してください。

適用対象

こちらもご覧ください