F#无法捕获TimeoutException

时间:2014-10-07 06:35:49

标签: exception f# timeout try-catch

我的问题非常简单。请看一下截图:

enter image description here

怎么会发生这种情况?我明确地将对Async.RunSyncron的调用放入try ... with

2 个答案:

答案 0 :(得分:2)

试试这个:

let withTimeout (timeOut: option<int>) (operation: Async<'x>) : Async<option<'x>> =
  match timeOut with
   | None -> async {
       let! result = operation
       return Some result
     }
   | Some timeOut -> async {
       let! child = Async.StartChild (operation, timeOut)
       try
         let! result = child
         return Some result
       with :? System.TimeoutException ->
         return None
     }

您不应在Async.RunSynchronously块中使用async,因为这样做会导致本机线程的使用不理想,并可导致stack overflowsAsync.RunSynchronously用于从此类计算之外运行Async次计算。在async块中,您可以使用普通let!do!,或者使用Async.StartChild来运行Async计算。这样可以更有效地使用本机线程,并且不会遇到潜在堆栈溢出的类似问题。

答案 1 :(得分:1)

F#异步工作流中的

try/with不直接映射到CLR保护块 - 相反,如果在用户代码中引发异常,库代码将捕获它并重新路由到最近的错误延续(可以是ie { {1}},with blockfinally block等中提供的自定义错误延续...)。这导致调试器可能会报告用户代码中未处理的异常,这些异常可以在以后处理和处理。

下面的代码片段报告调试器中的类似错误,但仍然执行成功完成

Async.StartWithContinuations