[英]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 上引發的異常?
兩種選擇:
MyTaskMethod
中捕獲異常我相信 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.