Try/catch 没有捕捉到 HttpListenerException

Try/catch not catching HttpListenerException

我使用 Grapevine(它只是 HttpListener 的接口)制作了一个简单的 http 端点。有时连接在我 SendResponse 之前断开,这会导致 HttpListenerException,但我不明白为什么 try/catch 不处理异常并且整个服务器崩溃。

错误:

Application: Movimiento de Placas.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
Stack:
   at System.Net.HttpResponseStream.Write(Byte[], Int32, Int32)
   at Grapevine.Interfaces.Server.HttpResponse.SendResponse(Byte[])
   at Grapevine.Server.HttpResponseExtensions.SendResponse(Grapevine.Interfaces.Server.IHttpResponse, System.String)
   at Grapevine.Server.Router.Route(System.Object)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

代码:

[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/patente")]
        public IHttpContext ModificarPantalla(IHttpContext context)
        {
            var dict = HttpUtility.ParseQueryString(context.Request.Payload);
            var json = new JavaScriptSerializer().Serialize(
                dict.Keys.Cast<string>()
                    .ToDictionary(k => k, k => dict[k]));
            var contenido = JsonConvert.DeserializeObject<Patente>(json);
            Server.FormRef.CargarPatente(contenido.Plate, contenido.idCamera);
            UltimaFoto.Fecha = DateTime.Now;
            Task.Run(() => Sqlite.InsertarPatente(contenido));
            try
            {
                context.Response.SendResponse(HttpStatusCode.Ok); //exception occurs here
            }
            catch (Exception ex)
            {

            }

            return context;
        }

如果 SendResponse 是异步的并且您没有等待它,则可能会发生这种情况。

这是一个已知问题。有一个 PR 已经存在了一段时间,现在修复了这个问题,我现在将它合并,以及一个将添加对 .NET Standard 的支持的更新。这应该在本周末之前可用。

Update: Grapevine 4.1.2 is available on Nuget.org as of August 9, 2019