首页 > 解决方案 > Giraffe F# 中的流式序列

问题描述

我想知道在 Giraffe 中流式传输 F# seq 的最简单方法是什么。不多,但这是我所拥有的:

  module HttpHandler =
    let handlerGuids : HttpHandler =
      handleContext(
          fun ctx ->
              task {
                  let collection =
                    seq {
                      let mutable i = 0
                      while (not ctx.RequestAborted.IsCancellationRequested) && i <10 do
                        i <- i + 1
                        Async.Sleep(2000) |> Async.RunSynchronously
                        yield Guid.NewGuid()
                      }
                  return! ctx.WriteJsonChunkedAsync collection
              })

    let router: HttpFunc -> HttpContext -> HttpFuncResult =
      choose [ route "/" >=> handlerGuids ]

我在 C# 中也有这个测试

    [Fact]
    public async void Test1()
    {
      using var httpClient = new HttpClient();
      httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
      var requestUri = "http://localhost:8080/";
      var stream = await httpClient.GetStreamAsync(requestUri);
      using var reader = new StreamReader(stream);
      while (!reader.EndOfStream) {
        var currentLine = reader.ReadLine();
      }
    }

但它会等到服务器上生成所有 guid。有人可以给我一些提示吗?Giraffe 文档中提到了流媒体,但它与文件有关。

标签: f#f#-giraffe

解决方案


推荐阅读