我使用Async.Catch来处理异步工作流抛出的异常:
work
|> Async.Catch
|> Async.RunSynchronously
|> fun x -> match x with
| Choice1Of2 _ -> () // success
| Choice2Of2 ex -> // failure, handle exception
今天我注意到Async.Catch不处理OperationCanceledExceptions。与其从Async.Catch获取Choice,异常会一直向上冒泡,直到它遇到我。我期望以下测试结果为红色,但实际为绿色:
[<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
如何处理异步工作流程的异常?我应该只使用try/catch块,而不是使用Async.Catch吗?