2016-08-15 6 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

あなたはasyncブロックでのtry/catchを置くところにも

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

1つの方法は、コールワークフローで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.CatchChoice<'T1,'T2>を返します。成功した実行の場合はChoice1Of2Choice2Of2の場合は例外がスローされます。

関連する問題