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 程式代碼可能會在進行取消要求時完成其工作,而且您的輪詢迴圈可能會遺漏 CancellationPending 設定為 true。 在這裡情況下,即使已提出取消要求,Cancelled事件處理程式中的 RunWorkerCompleted 旗標System.ComponentModel.RunWorkerCompletedEventArgs也不會設定為 true。 這種情況稱為 競爭條件 ,在多線程程序設計中是常見的考慮。 如需多線程設計問題的詳細資訊,請參閱 Managed 線程最佳做法

適用於

另請參閱