AggregateException没被捕获?

时间:2015-01-16 16:50:51

标签: 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()从未调用过?

1 个答案:

答案 0 :(得分:1)

我怀疑你此时并没有真正看到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;
}