2016-08-15 141 views
5

我有以下代碼。而且我想在不阻塞主線程的情況下運行。在Async.Start中捕獲異常?

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

因此,我將代碼更改爲以下內容。但是,如何在post中發現異常?

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

回答

1

你最好把try/catch語句在async塊以及

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

一種方法是在調用工作流中使用Async.Catch。鑑於一對夫婦的功能(暴殄天物 「異步」 功能,用的東西,結果工作):

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返回Choice<'T1,'T2>Choice1Of2成功執行,並拋出異常Choice2Of2