Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

BackgroundWorker.CancelAsync Method

Requests cancellation of a pending background operation.

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)
public void CancelAsync()

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.

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 void buttonCancel_Click(object sender, RoutedEventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
    {
        bw.CancelAsync();
    }
}


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

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

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.