Async.Catch doesnt work on OperationCanceledExceptions



我使用Async.Catch来处理异步工作流引发的异常:

work
|> Async.Catch
|> Async.RunSynchronously
|> fun x -> match x with
            | Choice1Of2 _ -> () // success
            | Choice2Of2 ex -> // failure, handle exception

今天我注意到OperationCanceledExceptions不是由Async.Catch处理的。而不是从Async获得Choice。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块吗?

取消是异步计算中的一种特殊异常。当工作流被取消时,这也会取消所有子计算(取消令牌是共享的)。因此,如果你可以将取消作为一个普通的异常处理,它仍然可以取消你计算的其他部分(很难对正在发生的事情进行推理)。

但是,您可以编写一个原语,启动工作流(并将其与父工作流分离),然后在此子工作流中处理取消。

type Async = 
  static member StartCatchCancellation(work, ?cancellationToken) = 
    Async.FromContinuations(fun (cont, econt, _) ->
      // When the child is cancelled, report OperationCancelled
      // as an ordinary exception to "error continuation" rather
      // than using "cancellation continuation"
      let ccont e = econt e
      // Start the workflow using a provided cancellation token
      Async.StartWithContinuations( work, cont, econt, ccont, 
                                    ?cancellationToken=cancellationToken) )

用法类似于Async.Catch,但必须将取消令牌传递给StartCatchCancellation,而不是传递给主RunSynchronously(因为工作流是单独启动的):

let work = 
  async { while true do
            do! Async.Sleep 100 }
let ct = new System.Threading.CancellationTokenSource(10000)
Async.StartCatchCancellation(work, ct.Token) 
|> Async.Catch
|> Async.RunSynchronously 
|> printfn "%A"

相关内容

  • 没有找到相关文章

最新更新