BackgroundWorker.CancelAsync BackgroundWorker.CancelAsync BackgroundWorker.CancelAsync BackgroundWorker.CancelAsync Method

定義

要求取消暫止的背景作業。 Requests cancellation of a pending background operation.

public:
 void CancelAsync();
public void CancelAsync ();
member this.CancelAsync : unit -> unit
Public Sub CancelAsync ()
例外狀況

範例

下列程式碼範例示範使用CancelAsync方法來取消非同步 (「 背景 」) 作業。The following code example demonstrates the use of the CancelAsync method to cancel an asynchronous ("background") operation. 此程式碼範例是針對提供之較大範例的一部分BackgroundWorker類別。This code example is part of a larger example provided for the BackgroundWorker class.

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 'cancelAsyncButton_Click

備註

CancelAsync 提交要求以中止暫止的背景作業,並設定CancellationPending屬性設trueCancelAsync submits a request to terminate the pending background operation and sets the CancellationPending property to true.

當您呼叫CancelAsync,背景工作方法,有機會先停止其執行和結束。When you call CancelAsync, your worker method has an opportunity to stop its execution and exit. 背景工作角色程式碼應該定期檢查CancellationPending屬性,以查看若將它設定trueThe worker code should periodically check the CancellationPending property to see if it has been set to true.

警告

請注意,您的程式碼中DoWork事件處理常式可能會完成其工作,進行取消要求,以及您輪詢迴圈可能會遺失CancellationPending設為trueBe aware that your code in the DoWork event handler may finish its work as a cancellation request is being made, and your polling loop may miss CancellationPending being set to true. 在此情況下,Cancelled旗標System.ComponentModel.RunWorkerCompletedEventArgs中您RunWorkerCompleted事件處理常式將不會設定為true,即使已取消要求。In this case, the Cancelled flag of System.ComponentModel.RunWorkerCompletedEventArgs in your RunWorkerCompleted event handler will not be set to true, even though a cancellation request was made. 這種情況稱為競爭情形和是多執行緒程式設計中常見的顧慮。This situation is called a race condition and is a common concern in multithreaded programming. 如需有關多執行緒的設計問題,請參閱Managed 執行緒最佳做法For more information about multithreading design issues, see Managed Threading Best Practices.

適用於

另請參閱