2016-08-15 1 views
5

다음 코드가 있습니다. 그리고 주 스레드를 차단하지 않고 실행하고 싶습니다.Async.Start에서 예외를 캡처합니까?

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

그래서 코드를 다음과 같이 변경했습니다. 그러나 post에서 예외를 catch하는 방법은 무엇입니까?

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 블록에서 시도/캐치를 넣어 줄뿐만 아니라

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.CatchChoice<'T1,'T2>을 반환합니다. 성공적으로 실행하려면 Choice1Of2, Choice2Of2에 대해서는 예외가 throw됩니다.

관련 문제