private void StartListening() { CheckIsDisposed(); ListeningStatus = ProcessStatus.WaitingToRun; Task.Run(async() => { try { ListeningStatus = ProcessStatus.Running; while (ListeningStatus == ProcessStatus.Running) { var lengthArray = new byte[sizeof(int)]; var readBytes = 0; do { readBytes += await _stream.ReadAsync(lengthArray, readBytes, lengthArray.Length - readBytes, _cancellationTokenSource.Token).ConfigureAwait(false); }while (readBytes < lengthArray.Length); _cancellationTokenSource.Token.ThrowIfCancellationRequested(); var length = BitConverter.ToInt32(lengthArray.Reverse().ToArray(), 0); if (length <= 0) { continue; } if (length > MaxMessageSize) { var exceptionMsg = $"Message length ({length}) is out of range (0 - {MaxMessageSize})"; throw new ArgumentOutOfRangeException(exceptionMsg); } var message = new byte[length]; readBytes = 0; do { readBytes += await _stream.ReadAsync(message, readBytes, message.Length - readBytes, _cancellationTokenSource.Token).ConfigureAwait(false); }while (readBytes < length); Streams.InvokeMessageStream(message); } ListeningStatus = ProcessStatus.Stopped; } catch (OperationCanceledException) { ListeningStatus = ProcessStatus.Stopped; } catch (Exception ex) { ListeningStatus = ProcessStatus.Error; if (!Streams.ListenerExceptionStream.Observers.Any()) { throw; } Streams.OnListenerException(ex); } }); }