BackgroundWorker.CancellationPending Property

Definition

Gets a value indicating whether the application has requested cancellation of a background operation.

public bool CancellationPending { get; }
[System.ComponentModel.Browsable(false)]
public bool CancellationPending { get; }

Property Value

true if the application has requested cancellation of a background operation; otherwise, false. The default is false.

Attributes

Examples

The following code example demonstrates the use of the CancellationPending property to query a BackgroundWorker about its cancellation state. This code example is part of a larger example provided for the BackgroundWorker class.

// Abort the operation if the user has canceled.
// Note that a call to CancelAsync may have set 
// CancellationPending to true just after the
// last invocation of this method exits, so this 
// code will not have the opportunity to set the 
// DoWorkEventArgs.Cancel flag to true. This means
// that RunWorkerCompletedEventArgs.Cancelled will
// not be set to true in your RunWorkerCompleted
// event handler. This is a race condition.

if (worker.CancellationPending)
{   
    e.Cancel = true;
}
else
{   
    if (n < 2)
    {   
        result = 1;
    }
    else
    {   
        result = ComputeFibonacci(n - 1, worker, e) + 
                 ComputeFibonacci(n - 2, worker, e);
    }

    // Report progress as a percentage of the total task.
    int percentComplete = 
        (int)((float)n / (float)numberToCompute * 100);
    if (percentComplete > highestPercentageReached)
    {
        highestPercentageReached = percentComplete;
        worker.ReportProgress(percentComplete);
    }
}

Remarks

If CancellationPending is true, then the CancelAsync method has been called on the BackgroundWorker.

This property is meant for use by the worker thread, which should periodically check CancellationPending and abort the background operation when it is set to true.

Applies to

Produs Versiuni
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

See also