3

如果我有这样的代码:

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()

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

4

1 回答 1

0

只要您Async.RunSynchronously在每个async工作流程上使用,您就一无所获。您需要编写一个完全异步的程序来利用它。然后你将能够同时做 10,000 个。

于 2013-10-19T01:20:13.723 回答