我有一个网络应用程序,它从外部服务获取数据。请求本身就像下面的代码一样发生——据我所知非常简单。创建一个请求,异步触发它并让回调处理响应。在我的开发环境中运行良好。
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
了同步执行请求,效果很好。在这些环境中,请求仍然超时,但没有造成任何损坏,并且应用程序在之后继续愉快地运行。
所以我已经解决了我的问题,但为什么会发生这种情况?任何人都可以启发我吗?:-)