AsyncCompletedEventArgs.Cancelled 属性

定义

获取一个值,该值指示异步操作是否已被取消。

public bool Cancelled { get; }

属性值

如果后台操作已被取消,则为 true;否则为 false。 默认值为 false

示例

下面的代码示例演示如何使用 AsyncOperation 来跟踪异步操作的生存期。 此代码示例是为 System.ComponentModel.AsyncOperationManager 类提供的一个更大示例的一部分。

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;
// 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时,异步操作已中断。

客户端应用程序的事件处理程序委托应在访问派生自 AsyncCompletedEventArgs的类中的任何属性之前检查 Cancelled 属性;否则,如果异步操作中断,该属性将引发 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

另请参阅