Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the best approach for serial data reception and processing using c#?
    primarykey
    data
    text
    <p>I am pretty new to coding with some experience in ASM and C for PIC. I am still learning high level programming with C#.</p> <p><strong>Question</strong></p> <p>I have a Serial port data reception and processing program in C#. To avoid losing data and knowing when it was coming, I set a <em>DataReceived</em> event and loop into the handling method until there were no more bytes to read.</p> <p>When I attempted this, the loop continued endlessly and blocked my program from other tasks (such as processing the retrieved data) when I continuously received data.</p> <p>I read about threading in C#, I created a thread that constantly checks for <em>SerialPort.Bytes2Read</em> property so it will know when to retrieve available data. </p> <p>I created a second thread that can process data while new data is still being read. If bytes have been read and ReadSerial() has more bytes to read and the timeout (restarted every time a new byte is read from the serial) they can still be processed and the frames assembled via a method named DataProcessing() which reads from the same variable being filled by ReadSerial().</p> <p>This gave me the desired results, but I noticed that with my solution (both <em>ReadSerial()</em> and <em>DataProcessing()</em> threads alive), CPU Usage was skyrocketed all the way to 100%!</p> <p>How do you approach this problem without causing such high CPU usage?</p> <pre><code>public static void ReadSerial() //Method that handles Serial Reception { while (KeepAlive) // Bool variable used to keep alive the thread. Turned to false { // when the program ends. if (Port.BytesToRead != 0) { for (int i = 0; i &lt; 5000; i++) { /* I Don't know any other way to implement a timeout to wait for additional characters so i took what i knew from PIC Serial Data Handling. */ if (Port.BytesToRead != 0) { RxList.Add(Convert.ToByte(Port.ReadByte())); i = 0; if (RxList.Count &gt; 20) // In case the method is stuck still reading BufferReady = true; // signal the Data Processing thread to } // work with that chunk of data. BufferReady = true; // signals the DataProcessing Method to work } // with the current data in RxList. } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload