/iBlue.ResxHelper/Src/AsyncHelpers.fs

http://github.com/fahadsuhaib/FSharpTools · F# · 51 lines · 27 code · 12 blank · 12 comment · 2 complexity · 5835a3333a4b9333dd9cd4c7b3689d34 MD5 · raw file

  1. namespace FSharp.Tutorial
  2. open System.Text
  3. open System.IO
  4. open Microsoft.FSharp.Control.WebExtensions
  5. [<AutoOpen>]
  6. module AsyncHelpers =
  7. type System.IO.StreamReader with
  8. /// An extension member to read all the lines from a stream reader asynchronously.
  9. ///
  10. /// In this implementation, the operation is pseduo-asynchronous.
  11. member reader.AsyncReadAllLines () =
  12. async { return [ while not reader.EndOfStream do
  13. yield reader.ReadLine()] }
  14. type System.Net.WebRequest with
  15. /// An extension member to write content into an WebRequest.
  16. ///
  17. /// In this implementation, the operation is pseduo-asynchronous.
  18. member req.AsyncWriteContent (content:string) =
  19. async { let bytes = Encoding.UTF8.GetBytes content
  20. req.ContentLength <- int64 bytes.Length
  21. use stream = req.GetRequestStream()
  22. stream.Write(bytes,0,bytes.Length) }
  23. /// An extension member to read all the content of a response to a WebRequest.
  24. ///
  25. /// In this implementation, the operation is pseduo-asynchronous.
  26. member req.AsyncReadResponse () =
  27. async { use! response = req.AsyncGetResponse()
  28. use responseStream = response.GetResponseStream()
  29. use reader = new StreamReader(responseStream)
  30. return reader.ReadToEnd() }
  31. /// An extension member to read all the content of a response to a WebRequest as a set of lines.
  32. ///
  33. /// In this implementation, the operation is pseduo-asynchronous.
  34. member req.AsyncReadResponseLines () =
  35. async { use! response = req.AsyncGetResponse()
  36. return [use stream = response.GetResponseStream()
  37. use reader = new StreamReader(stream)
  38. while not reader.EndOfStream do
  39. yield reader.ReadLine()] }