簡體   English   中英

有沒有辦法在任務不凍結 UI 的情況下處理任務引發的異常?

[英]Is there a way to handle exceptions thrown by a task without the task freezing the UI?

public async void CallTask()
{
    try
    {
        await Task.Run(MyTaskMethod);
    }
    catch (ArgumentException ex) // Exception doesn't get handled
    {
        MessageBox.Show(ex.Message);
    }
}

public Task MyTaskMethod()
{
    throw new ArgumentException("This is an error message"); 
}

我的任務引發了我想在更高級別捕獲的異常。

如何在不凍結 UI 的情況下處理 MyTaskMethod 上引發的異常?

兩種選擇:

  1. MyTaskMethod中捕獲異常
  2. 捕獲 Task 拋出的 AggregateException

我相信 1 是相當直截了當的理解。

2號看起來像這樣:

public async void CallTask()
{
    try
    {
        await Task.Run(MyTaskMethod);
    }
    catch (AggregateException ex) // Exception doesn't get handled
    {
        MessageBox.Show(ex.InnerExceptions[0].Message);
    }
}

public Task MyTaskMethod()
{
    throw new ArgumentException("This is an error message"); 
}

這是必要的,因為當在 Task 上引發異常時,它會在返回之前被包裝在 AggregateException 中。 這意味着試圖捕獲內部異常會失敗,所以我們需要先捕獲 AggregateException 然后再展開。

如果您使用消息框,則不能: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms0.message?

顯示消息 window,也稱為對話框,向用戶顯示消息。 它是一個模態 window,阻止應用程序中的其他操作,直到用戶關閉它。

您可以在表單中使用內聯標簽並設置 text 屬性,然后僅在出錯時顯示。

如果您的問題是未處理您的異常,請捕獲AggregateException https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library

要將所有異常傳播回調用線程,Task 基礎結構將它們包裝在 AggregateException 實例中。 AggregateException 異常有一個 InnerExceptions 屬性,可以枚舉該屬性以檢查引發的所有原始異常

public async void CallTask()
{
    try
    {
        await Task.Run(MyTaskMethod);
    }
    catch (AggregateException ex) // Exception does get handled
    {
        // access inner exceptions here. 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM