使用任务时 HttpListener 阻塞 task.delay

HttpListener blocking when using tasks and task.delay

所以在做个人项目写一个简单的http服务器。没有什么花哨。但我想使用任务来处理请求。所以我写了下面的代码,出于某种原因它是“阻塞”但不是真的?

所以我启动了服务器,然后在 chrome 中打开了两个单独的选项卡,我大致同时向服务器发送了一个请求。所以理论上两个请求都应该在大约 3 秒内完成。然而,第一个选项卡在 3 秒后加载,然后第二个选项卡在第一个选项卡后 3 秒加载,所以总共 6 秒。

有趣的是,服务器 运行 所在的主线程似乎没有被阻塞,但任务线程被阻塞了。我说主线程没有阻塞的原因是它在 while 循环中再次迭代并在启动 HandleRequestAsync 后立即到达“等待连接”的写入行。输出看起来像这样。如果第一次调用尚未完成,它似乎在第二次调用 HandleRequestAsync 时被阻止。

输出

Waiting for connection
Finished Connection
Waiting for connection
Delay over
Finished Connection
Waiting for connection
Delay over

代码

class Server
{
    private HttpListener listener { get; set; }
        
    private async Task HandleRequestAsync(HttpListenerRequest request, HttpListenerResponse response)
    {
        await Task.Delay(3000);
        Console.WriteLine("Delay over");

        response.ContentLength64 = 4;
        response.OutputStream.Write(Encoding.UTF8.GetBytes("Test"));

        response.OutputStream.Close();
    }

    public async Task StartServing()
    {
        listener.Start();

        while(true)
        {
            Console.WriteLine("Waiting for connection");

            var ctx = await listener.GetContextAsync().ConfigureAwait(false);

            HandleRequestAsync(ctx.Request, ctx.Response);

            Console.WriteLine("Finished Connection");
        }
    }
    public Server()
    {
        listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8000/");
    }
}

如问题评论所示。 Chrome 并且几乎所有网络浏览器都限制可以与一台主机建立多少个并发连接,即使它们位于不同的选项卡中也是如此。