AsyncCompletedEventArgs.Error 屬性

定義

取得值,指出非同步作業期間是否發生錯誤。

C#
public Exception Error { get; }
C#
public Exception? Error { get; }

屬性值

如果非同步作業期間發生錯誤,則為 Exception 執行個體,否則為 null

範例

下列程式代碼範例示範如何使用 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;
        }
    }
}

備註

如果在異步操作期間引發例外狀況,類別會將例外狀況指派給 Error 屬性。 用戶端應用程式的事件處理程式委派應該先檢查 屬性, Error 再存取衍生自 AsyncCompletedEventArgs的類別中的任何屬性;否則,屬性會引發 TargetInvocationException ,其 InnerException 屬性會具有 其 屬性的 Error參考。

Error如果工作已取消,則屬性值為 null

給繼承者的注意事項

如果您在衍生類別中提供唯讀屬性,請務必在屬性實作中呼叫 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

另請參閱