2016-08-15 4 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 ब्लॉक में ट्राई/कैच कर दिया था

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 उपयोग करने के लिए है। कार्यों की एक जोड़ी को देखते हुए (एक throwaway "async" समारोह और कुछ परिणाम के साथ काम करने के लिए):

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 के लिए अपवाद हटा दिया गया।

संबंधित मुद्दे