我使用 Async.Catch 来处理异步工作流引发的异常:
work
|> Async.Catch
|> Async.RunSynchronously
|> fun x -> match x with
| Choice1Of2 _ -> () // success
| Choice2Of2 ex -> // failure, handle exception
今天我注意到 OperationCanceledExceptions 不是由 Async.Catch 处理的。异常没有从 Async.Catch 获得选择,而是不断冒泡,直到它击中我。我预计以下测试是红色的,但它是绿色的:
[<Test>]
let ``Async.Catch doesnt work on OperationCancelledExceptions``() =
use cancellationTokenSource = new System.Threading.CancellationTokenSource(1000)
let work = async {
while true do
do! Async.Sleep 100
}
(fun () -> work
|> Async.Catch
|> fun x -> Async.RunSynchronously (x, cancellationToken=cancellationTokenSource.Token)
|> ignore)
|> should throw typeof<System.OperationCanceledException>
使用 Async.Catch + Choices + 匹配评估一些异常以及使用 try/catch 块评估其他一些异常似乎不正确......它看起来像下面这样,这太复杂了。除此之外,我想知道 Async.Catch 有什么用途,因为无论如何我都必须使用 try/catch 块......:
[<Test>]
let ``evaluating exceptions of async workflows``() =
use cancellationTokenSource = new System.Threading.CancellationTokenSource(1000)
let work = async {
while true do
do! Async.Sleep 100
}
try
work
|> Async.Catch
|> fun x -> Async.RunSynchronously (x, cancellationToken=cancellationTokenSource.Token)
|> fun x -> match x with
| Choice1Of2 result -> () // success, process result
| Choice2Of2 ex -> () // failure, handle exception
with ex -> () // another failure, handle exception here too
处理异步工作流异常的最佳方法是什么?我应该只转储 Async.Catch 并在任何地方使用 try/catch 块吗?