我正在嘗試將我的同步功能轉換為異步。在我的所有同步函式中,我都有一個取消令牌,用于函式、任務和并行塊。在呼叫異步函式之前我有一個 try/catch 塊,但是我得到了一個未處理的例外:
引發例外:System.Threading.Tasks.Parallel.dll 中的“System.OperationCanceledException” System.Threading.Tasks.Parallel.dll 中發生“System.OperationCanceledException”型別的例外,但未在用戶代碼中處理 操作已取消。
我的異步功能:
public async Task DecodeAsync(string? fileFullPath, FileDecodeType fileDecodeType, OperationProgress? progress = null) =>
await Task.Run(() => Decode(fileFullPath, fileDecodeType, progress), progress?.Token ?? default);
我怎么稱呼它:
try
{
await SlicerFile.DecodeAsync(fileName, fileDecodeType, Progress);
}
catch (OperationCanceledException) { } // Do not work!
catch (Exception exception) // Works for other exceptions
{
await this.MessageBoxError(exception.ToString(), "Error opening the file");
}
catch (OperationCanceledException)永遠不會到達,也不會catch (Exception exception)在取消事件中。由于我的嘗試最高,為什么它沒有捕獲例外?
但如果我這樣做:
public async Task DecodeAsync(string? fileFullPath, FileDecodeType fileDecodeType, OperationProgress? progress = null) =>
await Task.Run(() => throw new Exception("Test"));
我得到了通用例外的例外捕獲(已處理)
In other hand with old code it's working and handling the OperationCanceledException:
var task = await Task.Factory.StartNew( () =>
{
try
{
SlicerFile.Decode(fileName, fileDecodeType, Progress);
return true;
}
catch (OperationCanceledException) {} // Works!
catch (Exception exception)
{
Dispatcher.UIThread.InvokeAsync(async () =>
await this.MessageBoxError(exception.ToString(), "Error opening the file"));
}
return false;
});
What am I doing wrong?
uj5u.com熱心網友回復:
Task.Run 的結果不一定需要在那里等待。您可以只回傳正在運行的任務,然后該方法不再需要等待或異步。
Task DecodeAsync(string? fileFullPath, FileDecodeType fileDecodeType, OperationProgress? progress = null) => Task.Run(() =>
Decode(fileFullPath, fileDecodeType, progress), progress?.Token ?? default);
并且由于您正在使用令牌傳遞,因此您可以監視它以干凈地退出解碼方法,而不是嘗試捕獲并忽略操作取消的例外。
如果可以的話,如果您使解碼方法本身異步,您將會有更好的運氣。它已經回傳了一個任務,所以它可以回傳一個任務(或其他)。您的舊代碼也以同樣的方式異步,因此我可以看到您的新代碼沒有任何優勢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449985.html
標籤:c# asynchronous exception task
上一篇:我如何確定“最近的”例外處理程式
