private async Task AcceptClientsAsync(HttpListener server) { while (running) { try { var httpContext = await server.GetContextAsync(); if (!webSocketService.Handle(httpContext, cancellationTokenSource.Token) && !restService.Handle(httpContext)) { httpContext.Response.StatusCode = 404; httpContext.Response.Close(); } } catch (Exception ex) { if (server.IsListening) { logger.Error(ex, "Failed to handle connection"); } } } }