AsyncCompletedEventArgs.Cancelled 屬性

定義

取得值,指出非同步作業是否已取消。

C#
public bool Cancelled { get; }

屬性值

如果背景作業已取消,則為 true,否則為 false。 預設為 false

範例

下列程式代碼範例示範如何使用 AsyncOperation 來追蹤異步操作的存留期。 此程式代碼範例是提供給 類別之較大範例的 System.ComponentModel.AsyncOperationManager 一部分。

C#
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
C#
// This event handler updates the ListView control when the
// PrimeNumberCalculator raises the CalculatePrimeCompleted
// event. The ListView item is updated with the appropriate
// outcome of the calculation: Canceled, Error, or result.
private void primeNumberCalculator1_CalculatePrimeCompleted(
    object sender, 
    CalculatePrimeCompletedEventArgs e)
{
    Guid taskId = (Guid)e.UserState;

    if (e.Cancelled)
    {   
        string result = "Canceled";

        ListViewItem lvi = UpdateListViewItem(taskId, result);

        if (lvi != null)
        {
            lvi.BackColor = Color.Pink;
            lvi.Tag = null;
        }
    }
    else if (e.Error != null)
    {
        string result = "Error";

        ListViewItem lvi = UpdateListViewItem(taskId, result);

        if (lvi != null)
        {
            lvi.BackColor = Color.Red;
            lvi.ForeColor = Color.White;
            lvi.Tag = null;
        }
    }
    else
    {   
        bool result = e.IsPrime;

        ListViewItem lvi = UpdateListViewItem(
            taskId, 
            result, 
            e.FirstDivisor);

        if (lvi != null)
        {
            lvi.BackColor = Color.LightGray;
            lvi.Tag = null;
        }
    }
}

備註

Cancelled當 屬性為 true時,異步操作會中斷。

用戶端應用程式的事件處理程式委派應該先檢查 Cancelled 屬性,再存取衍生自 AsyncCompletedEventArgs之類別中的任何屬性;否則,如果異步操作中斷,屬性會引發 InvalidOperationException

給繼承者的注意事項

如果您在衍生類別中提供唯讀屬性,請務必呼叫 RaiseExceptionIfNecessary() 方法。 這可防止用戶端存取因異步操作失敗而可能無效的屬性。

適用於

產品 版本
.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

另請參閱