发生异常时的HttpWebRequest异步调用执行顺序

HttpWebRequest async call execution order when exception occurs

我使用 HttpWebRequest 异步调用 Web 服务,偶尔 EndGetResponse() returns 一些异常。然而,即使我得到异常,调用成功并返回数据。以下是我的代码,删除了错误检查代码。我得到了 4 个日志项,顺序是这样的:

返回以下结果:...
获取结果成功!
PostXML 异常:...
GetResult 异常:...

    public async Task<string> GetResult(string xmlData)
    {
        try
        {
            string response = await PostXML(Url, xmlData).ConfigureAwait(false);
            _logger.Log($"GetResult is successful!");
            return response;
        }
        catch (Exception ex)
        {
            _logger.Log("GetResult exception: " + ex.ToString());
            throw;
        }
    }

    private async Task<string> PostXML(string destinationUrl, string requestXml)
    {
        try
        {
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)await Task.Factory
                .FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
                _logger.Log("The following result is returned: \r\n" + responseStr);
                responseStream.Close();
                return responseStr;
            }
        }
        catch (Exception ex)
        {
            _logger.Log("PostXML exception: " + ex.ToString());
            throw;
        }
        return null;
    }

异常是这样的:
PostXML() 异常:System.Net.WebException:基础连接已关闭:服务器关闭了预期保持活动状态的连接。
在 System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
在 System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction,Action1 endAction, Task1 promise,Boolean requiresSynchronization)
--- 从先前抛出异常的位置开始的堆栈跟踪结束 ---
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在 MyService.d__7.MoveNext()

我想我还没有完全理解 HttpWebRequest 在异步模式下是如何工作的。无论如何,我希望这些问题可以帮助我更多地理解它:
1。为什么出现异常还继续执行?据我了解,应该只有 2 个日志项来记录异常。
2。出现异常"The underlying connection was closed"的原因是什么?为什么出现了异常,服务还是返回了正确的结果?

Why does the execution continue even an exception occurs? In my understanding, there should only have 2 log items to log the exception.

这是不可能的。我怀疑您的代码调用了 GetResult 两次。这就是日志似乎表明的内容。

What is the reason the exception "The underlying connection was closed" occurs?

当服务器在客户端准备好关闭连接之前关闭连接时,就会发生这种情况。这是从 REST API 得到的异常错误,但并非闻所未闻。