gpt4 book ai didi

c# - 异步 Web 请求超时 => 使 IIS 崩溃

转载 作者:太空狗 更新时间:2023-10-29 21:06:01 25 4
gpt4 key购买 nike

我有一个网络应用程序,它从外部服务获取数据。请求本身就像下面的代码一样——据我所知非常简单。创建一个请求,异步触发它并让回调处理响应。在我的开发环境中运行良好。

public static void MakeRequest(Uri uri, Action<Stream> responseCallback)
{
WebRequest request = WebRequest.Create(uri);
request.Proxy = null;
request.Timeout = 8000;
try
{
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith(task =>
{
WebResponse response = task.Result;
Stream responseStream = response.GetResponseStream();
responseCallback(response.GetResponseStream());
responseStream.Close();
response.Close();
});
} catch (Exception ex)
{
_log.Error("MakeRequest to " + uri + " went wrong.", ex);
}
}

但是,由于我以外的原因,外部测试环境和生产环境可能无法访问目标 URL。好吧,我想——请求超时不会真正伤害到任何人。然而,似乎每次这个请求超时时,ASP.NET 崩溃并且 IIS 被重新启动。事件日志向我显示了这个堆栈跟踪:

StackTrace:    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.get_Result()
at MyApp.AsyncWebClient.<>c__DisplayClass2.<MakeRequest>b__0(Task`1 task)
at System.Threading.Tasks.Task`1.<>c__DisplayClass17.<ContinueWith>b__16(Object obj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()

InnerException: System.Net.WebException

Message: Unable to connect to the remote server

StackTrace: at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endMethod, TaskCompletionSource`1 tcs)

InnerException: System.Net.Sockets.SocketException

Message: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

StackTrace: at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

..所以在我看来,这一切都归结为 SocketException。紧接着(在同一秒内)记录了另一个事件(我猜是相关的):

Exception Info: System.AggregateException
Stack:
at System.Threading.Tasks.TaskExceptionHolder.Finalize()

这有点超出我的理解范围,因为我不是异步代码和线程的专家,但是 Web 请求的超时导致 IIS 崩溃似乎很奇怪。我重新实现了 MakeRequest 以同步执行请求,效果很好。在这些环境中,请求仍然会超时,但不会造成任何损坏,并且应用程序会在之后继续愉快地运行。

所以我已经解决了我的问题,但为什么会这样呢?谁能启发我? :-)

最佳答案

您的延续需要处理 .Result 可能反射(reflect)异常的事实。否则你有一个未处理的异常。未处理的异常终止进程。

.ContinueWith(task =>
{
try {
WebResponse response = task.Result;
Stream responseStream = response.GetResponseStream();
responseCallback(responseStream);
responseStream.Close();
response.Close();
} catch(Exception ex) {
// TODO: log ex, etc
}
});

您的异常处理程序仅涵盖任务的创建 - 不包括回调。

关于c# - 异步 Web 请求超时 => 使 IIS 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10818239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com