다음을 통해 공유


BackgroundWorker.CancelAsync Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Requests cancellation of a pending background operation.

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)

Syntax

'Declaration
Public Sub CancelAsync
public void CancelAsync()

Exceptions

Remarks

The CancelAsync method submits a request to stop the background operation and sets the CancellationPending property to true.

When you call CancelAsync, your background operation will be able to stop and exit. The operation code should periodically check the CancellationPending property to see whether it has been set to true.

Caution noteCaution:

Be aware that your code in the DoWork event handler may complete its work as a cancellation request is being made, and your polling loop may miss CancellationPending being set to 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. For more information about multithreading design issues, see Best Practices for Managed Threading.

Examples

The following code example demonstrates the use of the CancelAsync method to cancel a background operation. To view the complete code for this sample, see How to: Use a Background Worker.

Private Sub buttonCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    If bw.WorkerSupportsCancellation = True Then
        bw.CancelAsync()
    End If
End Sub
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
    {
        bw.CancelAsync();
    }
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.