public virtual void Read() { while (_isMonitoring) { try { if (_cancellationTokenSource != null && _cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource.Token.ThrowIfCancellationRequested(); } // Sometimes the serial port lib will throw an exception and read past the end of the queue if a // status changes while data is being written. We just ignore these bytes. var b = Reader.ReadByte(); ReadBuffer.Enqueue(b); DataAvailable(false); } catch (OperationCanceledException ex) { _cancellationTokenSource.Dispose(); _cancellationTokenSource = null; _isMonitoring = false; Debug.WriteLine($"Read Cancelled Exception: {ex.Message}"); } }
private void Init() { Writer = () => { while (Executing) { if (WriteBuffer.Count > 0) { lock (WriteBuffer) { if (WriteBuffer.Count > 0) { var e = WriteBuffer.Dequeue(); //Debug.WriteLine($"Computer reads {e}"); return(e); } Thread.Sleep(1); } } } return(-1); }; Reader = l => { lock (ReadBuffer) { //Debug.WriteLine($"Computer writes {l}"); ReadBuffer.Enqueue(l); } }; }
protected virtual async void ReadLongRunningTask() { while (true) { if (_readCancellationTokenSource != null && _readCancellationTokenSource.IsCancellationRequested) { Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Read Long-Running Task Cancellation was requested.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName); break; } await Task.Delay(100); if (Reader == null) { continue; } if (!IsConnected) { continue; } try { // Sometimes the serial port lib will throw an exception and read past the end of the queue if a // status changes while data is being written. We just ignore these bytes. var b = Reader.BaseStream.ReadByte(); if (b >= 0 && b <= 255) { ReadBuffer.Enqueue((byte)b); DataAvailable(); } } //catch (OperationCanceledException ex) //{ // try // { // _readCancellationTokenSource.Dispose(); // _readCancellationTokenSource = null; // //_isMonitoring = false; // } // catch // { // Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Swallowing OperationCanceledException... secondary issue during dispose of cancellation token."); // } // Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Swallowing OperationCanceledException... this is used to turn off status monitoring."); //} catch (Exception ex) { // Swallow the exception //Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Swallowing generic read exception... sometimes happens with serial port printers.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName); } } }