When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

前端 未结 3 989
悲&欢浪女
悲&欢浪女 2020-12-08 18:42

I am using the System.Net.Http.HttpClient to do some client-side HTTP communication. I\'ve got all of the HTTP in one spot, abstracted away from the rest of the code. In one

3条回答
  •  醉话见心
    2020-12-08 19:33

    You can also take stream as input parameter, so the caller has complete control over type of the stream as well as its disposal. And now you can also dispose httpResponse before control leaves the method.
    Below is the extension method for HttpClient

        public static async Task HttpDownloadStreamAsync(this HttpClient httpClient, string url, Stream output)
        {
            using (var httpResponse = await httpClient.GetAsync(url).ConfigureAwait(false))
            {
                // Ensures OK status
                response.EnsureSuccessStatusCode();
    
                // Get response stream
                var result = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
    
                await result.CopyToAsync(output).ConfigureAwait(false);
                output.Seek(0L, SeekOrigin.Begin);                
            }
        }
    

提交回复
热议问题