public static async void SendResponse(ResponseEntity data, HttpListenerContext currentContext) { await Task.Run(async() => { try { data.ParseHeadersIntoContext(currentContext); var byteBuffer = data.GetDataAsBytes(); currentContext.Response.ContentLength64 = byteBuffer.Length; await currentContext.Response.OutputStream.WriteAsync(byteBuffer, 0, byteBuffer.Length); currentContext.Response.OutputStream.Close(); var eventData = new ServerEventData { status = currentContext.Response.StatusCode, exception = null, message = currentContext.Request.HttpMethod, path = currentContext.Request.Url.AbsolutePath }; onRequestFinishedProcessing?.Invoke(eventData); } catch (Exception e) { try { throw new InternalServerErrorException(e.Message, currentContext, e); } catch (InternalServerErrorException ex) { ExceptionHandler.HandleException(ex, currentContext); } } }); }