c# - 何时或是否在调用 ReadAsStreamAsync 时处理 HttpResponseMessage?

标签 c# .net stream idisposable dotnet-httpclient

我正在使用 System.Net.Http.HttpClient做一些客户端 HTTP 通信。我将所有 HTTP 放在一处,从其余代码中抽象出来。在一个实例中,我想将响应内容作为流读取,但流的使用者与发生 HTTP 通信和打开流的位置完全隔离。在负责 HTTP 通信的地方,我处理了所有 HttpClient 东西。

此单元测试将在 Assert.IsTrue(stream.CanRead) 处失败:

[TestMethod]
public async Task DebugStreamedContent()
{
    Stream stream = null; // in real life the consumer of the stream is far away 
    var client = new HttpClient();        
    client.BaseAddress = new Uri("https://www.google.com/", UriKind.Absolute);

    using (var request = new HttpRequestMessage(HttpMethod.Get, "/"))
    using (var response = await client.SendAsync(request))
    {
        response.EnsureSuccessStatusCode();
        //here I would return the stream to the caller
        stream = await response.Content.ReadAsStreamAsync();
    }

    Assert.IsTrue(stream.CanRead); // FAIL if response is disposed so is the stream
}

我通常会尝试尽早处理任何 IDisposable,但在这种情况下,处理 HttpResponseMessage 也会处理返回的 Stream来自 ReadAsStreamAsync

所以调用代码似乎需要了解响应消息和流并获得其所有权,或者我不处理响应消息,让终结器处理它。两种选择都感觉不对。

This answer讨论不处理 HttpClientHttpRequestMessage 和/或 HttpResponseMessage 怎么样?

我错过了什么吗?我希望让消费代码对 HTTP 一无所知,但将所有这些未处理的对象留在身边有悖于多年的习惯!

最佳答案

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.

在这种特定情况下,没有终结器HttpResponseMessageHttpRequestMessage 都没有实现终结器(这是一件好事!)。如果您不处理它们中的任何一个,一旦 GC 启动,它们将被垃圾收集,一旦发生,它们的底层流的句柄将被收集。

只要您正在使用这些对象,就不要处置。完成后,处理掉它们。无需将它们包装在 using 语句中,您始终可以在完成后显式调用 Dispose。无论哪种方式,使用代码都不需要了解任何 HTTP 请求的基础知识。

关于c# - 何时或是否在调用 ReadAsStreamAsync 时处理 HttpResponseMessage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27715327/

相关文章:

javascript - Angular 和 ASP.NET MVC - 后端收到时参数为空

c# - 来自无法访问的代码的无法捕获的异常

c# - LINQ to NHibernate 和 let 关键字

c# - 无偏时间系统 C#

.net - ASP.NET 优化不会将 LESS 转换为 CSS

.net - PowerShell/获取枚举器

c++ - 如何清除String流中的内容?

c# - 无法通过 TCP/Sockets .net 退出具有多个缓冲区传输的循环

javascript - 是否可以发布 responseType : 'stream' in Axios?

c# - 附加信息 : Attempted to read or write protected memory. 这通常表示其他内存已损坏