【问题标题】:InvalidOperationException when disposing a HttpContent object while being read读取时释放 HttpContent 对象时出现 InvalidOperationException
【发布时间】:2014-12-02 21:39:33
【问题描述】:

首先,我使用 Stephen Toub 的 WithCancellation 扩展来允许我中止 ReadStringAsync 方法。这在内部使用TaskCompletionSourceTasks.WhenAny。详情在这里; http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx

由于Using 关键字,异常被抛出。当End Using 被命中时,读取仍在进行中,这会释放Response.Content 对象的内部流。我知道读取仍在后台运行,只要我的代码可以继续运行而不会卡在长时间读取中,我不介意。

我不确定HttpClient 的超时属性在进行这种读取时是否适用(请求是使用HttpCompletionOption.ResponseHeadersRead 发出的,所以在读取之前我没有内容)。另外,由于代理错误,我可能会遇到代码卡在读取中的问题,因此我需要能够取消它。

我不明白的是;

  1. 为什么我的 try/catch 块没有捕获到异常?
  2. 如何解决此问题,以便中止读取并忽略异常?

无法删除Using 块,因为所有HttpReponseMessage 对象都包装在Using 中,所以当HttpResponseMessage 被释放时,我遇到了同样的问题。

  Public Async Function GetResponseStringAsync(Response As HttpResponseMessage) As Tasks.Task(Of String)

    Dim TimeoutToken As New CancellationTokenSource
    TimeoutToken.CancelAfter(DefaultTimeout)

    Try

      Using Response.Content
        Try
          Return Await Response.Content.ReadAsStringAsync.WithCancellation(TimeoutToken.Token).ConfigureAwait(False)
        Catch ex As Exception
        End Try
      End Using
    Catch ex As Exception

    End Try

    Return Nothing
  End Function

这是被抛出的InvalidOperationException 的输出。

System.InvalidOperationException: Can not access a closed Stream.
   at System.Net.GZipWrapperStream.EndRead(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.EndRead(IAsyncResult asyncResult)
   at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)

编辑:72 小时后没有 cmets、upvotes 或答案。这个问题有问题吗?

【问题讨论】:

    标签: .net vb.net stream task-parallel-library using


    【解决方案1】:

    Response.Content.ReadAsStringAsync 的调用不会阻塞。它立即返回(毕竟它是异步的),这会触发 using 语句的 finally 子句中对 Content 的 Dispose 调用,从而关闭底层流并因此导致异常。

    在尝试读取时,流已经关闭。要在阅读后处理内容,您可以使用这样的延续:

    ContinueWith(t => { response.Content.Dispose(); return t.Result; });
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 2010-12-30
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多