异步代码+ Async.RunSynchronously与普通同步代码

时间:2013-10-16 14:34:31

标签: multithreading asynchronous f#

如果我有这样的代码:

let asyncReadToEnd (stream:Stream) = async {
  // Allocate 4kb buffer for downloading data
  let buffer = Array.zeroCreate (4 * 1024)
  use output = new MemoryStream()
  let reading = ref true

  while reading.Value do
    // Download one (at most) 4kb chunk and copy it
    let! count = stream.AsyncRead(buffer, 0, buffer.Length)
    output.Write(buffer, 0, count)
    reading := count > 0

  // Read all data into a string
  output.Seek(0L, SeekOrigin.Begin) |> ignore

  use sr = new StreamReader(output)
  return sr.ReadToEnd() 
}

use stream = httpResponse.GetResponseStream()
asyncReadToEnd stream |> Async.RunSynchronously

与简单地做

相比,我获得了什么
use stream = httpResponse.GetResponseStream()
use sr = new StreamReader(stream)
sr.ReadToEnd()

在这两种情况下,我都会阻止当前线程,但是在使用第一个版本释放线程资源方面还有什么优势吗?

1 个答案:

答案 0 :(得分:0)

只要您在每个Async.RunSynchronously工作流程中使用async,您就什么都得不到。您需要编写一个完全异步的程序来利用它。然后你可以同时做10,000个。