Created
November 21, 2011 20:29
-
-
Save davidgrenier/1383824 to your computer and use it in GitHub Desktop.
Catching async request timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| open System | |
| open System.IO | |
| open System.Net | |
| type Request = Request of WebRequest * AsyncReplyChannel<WebResponse> | |
| let requestAgent = | |
| MailboxProcessor.Start <| fun inbox -> async { | |
| while true do | |
| let! (Request (req, port)) = inbox.Receive () | |
| async { | |
| try | |
| let! resp = req.AsyncGetResponse () | |
| port.Reply resp | |
| with | |
| | ex -> sprintf "Exception in child %s\n%s" (ex.GetType().Name) ex.Message |> Console.WriteLine | |
| } |> Async.Start | |
| } | |
| let getHTML url = | |
| async { | |
| try | |
| let req = "http://" + url |> WebRequest.Create | |
| try | |
| use! resp = requestAgent.PostAndAsyncReply ((fun chan -> Request (req, chan)), 1000) | |
| use str = resp.GetResponseStream () | |
| use rdr = new StreamReader (str) | |
| return Some <| rdr.ReadToEnd () | |
| with | |
| | :? System.TimeoutException -> | |
| req.Abort() | |
| Console.WriteLine "RequestAgent call timed out" | |
| return None | |
| with | |
| | ex -> | |
| sprintf "Exception in request %s\n%s" (ex.GetType().Name) ex.Message |> Console.WriteLine | |
| return None | |
| } |> Async.RunSynchronously;; | |
| getHTML "www.grogogle.com" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment