Search code examples
f#httpclient

F# HttpClientHandler Dispose


While it's generally advised not to create an instance of HttpClient for each request, there might be exceptions, like when an instance is conditionally created based on whether a proxy should be used. The following snippet illustrates this, but it doesn't provide an opportunity for HttpClientHandler to be disposed. So, what is the correct approach to handle this?

use httpClient =
    if System.String.IsNullOrWhiteSpace apiHttpProxy |> not then
        let httpClientHandler =
            new HttpClientHandler(Proxy = WebProxy(System.Uri(apiHttpProxy), true))

        new HttpClient(httpClientHandler, true)
    else
        new HttpClient()

Solution

  • HttpClient has constructor, which has boolean argument specifying, whether handler should be automatically disposed on client dispose. see details here

    And I see you already have it in your example, so you don‘t need to do anything else.