private async Task StartListenerAsync() { try { _tcpListener.Start(); while (_isListening) { // Await request. var client = await _tcpListener.AcceptTcpClientAsync().ConfigureAwait(false); var request = new HttpListenerRequest(client); // Handle request in a separate thread. Task.Run(async() => { // Process request. var response = new HttpListenerResponse(request, client); try { await request.ProcessAsync(); response.Initialize(); if (_handler == null) { // No Request handler exist. Respond with "Not Found". response.NotFound(); response.Close(); } else { // execute handler. _handler.HandleContext(new HttpListenerContext(request, response)); } } catch (Exception) { response.CloseSocket(); } }); testL++; } } finally { _isListening = false; _cts = null; } }
private async Task StartListenerAsync() { _tcpListener.Start(); while (!_cancellationToken.IsCancellationRequested) { // Await request. var client = await _tcpListener.AcceptTcpClientAsync().ConfigureAwait(false); _cancellationToken.ThrowIfCancellationRequested(); var request = new HttpListenerRequest(client, _cancellationToken); // Handle request in a separate thread. Task.Run(async() => { // Process request. var response = new HttpListenerResponse(request, client); try { await request.ProcessAsync(); response.Initialize(); _cancellationToken.ThrowIfCancellationRequested(); if (_handler == null) { // No Request handler exist. Respond with "Not Found". response.NotFound(); response.Close(); } else { // execute handler. _handler.HandleContext(new HttpListenerContext(request, response), _cancellationToken); } } catch (Exception) { response.CloseSocket(); } }); } }