Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 捕获在不同线程上运行的异步工作流的异常_Asynchronous_F# - Fatal编程技术网

Asynchronous 捕获在不同线程上运行的异步工作流的异常

Asynchronous 捕获在不同线程上运行的异步工作流的异常,asynchronous,f#,Asynchronous,F#,此代码未捕获异常。如何在单独的线程上启动异步工作流并在主程序中捕获异常?由于没有等待的结果,因此无法捕获异常。您需要包装计算。一种可能性: let failing = async { failwith "foo" } let test () = try Async.Start(failing) with | exn -> printf "caught" 作为替代方案,您可以将工作流作为任务启动,并使用其方法和属性。例如,Task.Resu

此代码未捕获异常。如何在单独的线程上启动异步工作流并在主程序中捕获异常?

由于没有等待的结果,因此无法捕获异常。您需要包装计算。一种可能性:

let failing = async {
    failwith "foo"
}

let test () =
    try
        Async.Start(failing)
    with
    | exn -> printf "caught"

作为替代方案,您可以将工作流作为任务启动,并使用其方法和属性。例如,
Task.Result
将再次重新引发异常,这样就可以工作了,这几乎就是您所尝试的:

let failing = async {
    failwith "foo"
}

let test () = 
    async {
        let! res = failing |> Async.Catch
        match res with
        | Choice1Of2 _ -> printf "success"
        | Choice2Of2 exn -> printfn "failed with %s" exn.Message
    } |> Async.Start

在不同的线程上 抱歉-我刚刚看到您希望它位于不同的线程上-在这种情况下,您很可能希望使用RCH提供给您的内部方法-但是您也可以使用
ContinueWith
(尽管有点难看):


Async.Catch
此外,您实际上不需要
Async.Catch

> test ();;
caught
val it : Task = System.Threading.Tasks.Task {AsyncState = null;
                                             CreationOptions = None;
                                             Exception = null;
                                             Id = 3;
                                             IsCanceled = false;
                                             IsCompleted = true;
                                             IsFaulted = false;
                                             Status = RanToCompletion;}
> test ();;
caught
val it : unit = ()
open System.Threading.Tasks

let test () = 
   (Async.StartAsTask failing).ContinueWith(fun (t : Task<_>) -> try t.Result with _ -> printfn "caught")
> test ();;
caught
val it : Task = System.Threading.Tasks.Task {AsyncState = null;
                                             CreationOptions = None;
                                             Exception = null;
                                             Id = 3;
                                             IsCanceled = false;
                                             IsCompleted = true;
                                             IsFaulted = false;
                                             Status = RanToCompletion;}
let test () = 
   async { 
      try 
         do! failing 
      with _ -> printfn "caught" 
   } |> Async.Start