HttpClient vs HttpWebRequest

前端 未结 3 1248
一向
一向 2020-12-02 15:27

I have a large file which I have to send to a web api client...The data is multi part. The issue is , if the file is sent over http web request, then it is uploaded quickly

3条回答
  •  情话喂你
    2020-12-02 16:02

    Perhaps you were instantiating HttpClient in a using block which could explain performance issues. E.g.

      using (var httpClient = new HttpClient() )
      {
          var result = await httpClient.GetAsync("http://example.com");
          Console.WriteLine(result.StatusCode);
      }
    

    Here the instance of HttpClient is being disposed immediately after the request whereas it should arguably be a long lived object (E.g. the lifetime of the application).

    [edit - added context]

    Disposing the instance also closes the connection but leaves the socket in a waiting state for a set duration. For each execution of this code, the os will attempt to create a new socket connection, and since there is a limit to how quickly this can be completed, performance/reliability issues can arise.

    Reusing the same HttpClient instance means better reuse of open sockets and more efficient use of system resources.

    More info here.

提交回复
热议问题