Exclude capture in Async.Start?

I have the following code. And I want to run without blocking the main thread.

let post () = ..... try let response = post () logger.Info(response.ToString()) with | ex -> logger.Error(ex, "Exception: " + ex.Message) 

So, I changed the code to the following. However, how to catch an exception in post ?

 let post = async { .... return X } try let response = post |> Async.StartChild logger.Info(response.ToString()) with | ex -> logger.Error(ex, "Exception: " + ex.Message) 
+5
source share
2 answers

You also put try / catch in the async block

 let post = async { .... } async { try let! response = post logger.Info(response.ToString()) with | ex -> logger.Error(ex, "Exception: " + ex.Message) } |> Async.Start 
+1
source

One way is to use Async.Catch in the call workflow. Given a couple of functions (an "asynchronous" function and something to work with the result):

 let work a = async { return match a with | 1 -> "Success!" | _ -> failwith "Darnit" } let printResult (res:Choice<'a,System.Exception>) = match res with | Choice1Of2 a -> printfn "%A" a | Choice2Of2 e -> printfn "Exception: %s" e.Message 

One can use Async.Catch

 let callingWorkflow = async { let result = work 1 |> Async.Catch let result2 = work 0 |> Async.Catch [ result; result2 ] |> Async.Parallel |> Async.RunSynchronously |> Array.iter printResult } callingWorkflow |> Async.RunSynchronously 

Async.Catch returns a Choice<'T1,'T2> . Choice1Of2 for success and exception thrown for Choice2Of2 .

+2
source

All Articles