聚合异常未被捕获

  • 本文关键字:异常 c# exception stream
  • 更新时间 :
  • 英文 :


>我正在查询远程服务器,有时会得到AggregateException.这种情况相当罕见,我知道发生这种情况时如何解决,但由于某种原因,每当抛出异常时,它都不会进入catch块。

这是 catch 块的代码部分:

try
{
    using (Stream stream = await MyQuery(parameters))
    using (StreamReader reader = new StreamReader(stream))
    {
        string content = reader.ReadToEnd();
        return content;
    }
}
catch (AggregateException exception)
{
    exception.Handle((innerException) =>
    {
        if (innerException is IOException && innerException.InnerException is SocketException)
        {
            DoSomething();
            return true;
        }
        return false;
    });
}

这是我收到的异常消息:

System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---

我假设那些 -->箭头表明这是一个内部例外,对吧?那么,如果是IOException -> SocketException,为什么DoSomething()从不调用?

我怀疑你现在实际上并没有看到AggregateException。您拥有的代码中没有任何内容在执行并行操作。

如果这是正确的,你应该能够做这样的事情:

try
{
  using (Stream stream = await MyQuery(parameters))
  using (StreamReader reader = new StreamReader(stream))
  {
    string content = reader.ReadToEnd();
    return content;
  }
}
catch (IOException exception)
{
  if (exception.InnerException is SocketException)
    DoSomething();
  else
    throw;
}

相关内容

  • 没有找到相关文章

最新更新