When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

前端 未结 3 986
悲&欢浪女
悲&欢浪女 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:19

    So it seems like the calling code needs to know about and take ownership of the response message as well as the stream, or I leave the response message undisposed and let the finalizer deal with it. Neither option feels right.

    In this specific case, there are no finalizers. Neither HttpResponseMessage or HttpRequestMessage implement a finalizer (and that's a good thing!). If you don't dispose of either of them, they will get garbage collected once the GC kicks in, and the handle to their underlying streams will be collected once that happens.

    As long as you're using these objects, don't dispose. Once done, dispose of them. Instead of wrapping them in a using statement, you can always explicitly call Dispose once you're done. Either way the consuming code doesn't need to have any knowledge underlying http requests.

提交回复
热议问题