private async Task ReaderThread(CancellationToken ct) { while (true) { ct.ThrowIfCancellationRequested(); try { await _readerSemaphore.WaitAsync(ct); ct.ThrowIfCancellationRequested(); _readerStream.Position = 0; var count = await _pipe.CopyMessageToAsync(_readerStream, ct); if (count == 0) { _readerSemaphore.Release(); Stop(); await StartAsync().ConfigureAwait(false); return; } _readerStream.Position = 0; var request = await _messageSerializer.DeserializeAsync <ApiRequest>(_readerStream).ConfigureAwait(false); if (request == null) { continue; } var requestProcessor = _requestProcessorFactory.Create(request.Resource); var response = await requestProcessor.ProcessAsync(request.Action, request.Content).ConfigureAwait(false); await Task.Run(() => _pipe.WaitForPipeDrain()).ConfigureAwait(false); await _messageSerializer.SerializeAsync(_pipe, response).ConfigureAwait(false); _readerSemaphore.Release(); } catch (OperationCanceledException) { _readerSemaphore.Release(); return; } catch (Exception ex) { _logger.Error(ex); _readerSemaphore.Release(); Stop(); await StartAsync().ConfigureAwait(false); } } }