private void Run() { var buffer = new byte[BufferSize]; try { while (!CancelEvent.WaitOne(0, false)) { lock (UartLock) { try { while (Uart.BytesToRead > 0) { var readLength = Uart.Read(buffer, 0, buffer.Length); if (readLength > 0) { ProcessRawBytesAndReturnResponse(buffer, readLength); } } } catch (TimeoutException) { } catch (InvalidOperationException) { } //probably unplugged while (MessageQueue.Count > 0) { var e = new CanankaMessageEventArgs(MessageQueue.Dequeue()); OnMessageArrived(e); } if (!Uart.IsOpen) { break; } //exit thread as port is closed Thread.Sleep(1); } } } catch (ThreadAbortException) { } }
/// <summary> /// Raises MessageArrived trigger. /// If thread used to create object had synchronization context (e.g. main window loop), that context will be used for event processing. /// </summary> /// <param name="e">Arguments.</param> protected void OnMessageArrived(CanankaMessageEventArgs e) { if (Context != null) { Context.Post((object state) => { MessageArrived?.Invoke(this, state as CanankaMessageEventArgs); }, e); } else { MessageArrived?.Invoke(this, e); } }