Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Instead of a timer I would use double-buffering with a lock or mutex to control access to the buffer which would be a shared resource for reading and writing. Also, the SerialPort.Read(byte[],int,int) method when called from inside the SerialPort.DataReceived event is already automatically executed on a new thread. </p> <p>The problem comes when you try to read and write to the same memory location at the same time. One way around this is to use 2 buffers (arrays of type byte) and write to one of them while your graphing code reads from the other. In this case the buffers are called shared resources and their access should be regulated. You can use a lock but I usually use one mutex for each buffer. After you instantiate a mutex you call the "WaitOne" method which will force any other code that wants to use the shared resource to wait until the mutex is released. It might look something like this.</p> <pre><code> void OnDataReceived(object sender, SerialDataReceivedEventArgs e) { if (writeToBuffer1) { numToRead1 = SerialPort.BytesToRead; mutex1.WaitOne(); numRead1 = SerialPort.Read(buffer1, 0, numToRead1); mutex1.ReleaseMutex(); writeToBuffer1 = false; PlotData(buffer1, numRead1); } else { numToRead2 = SerialPort.BytesToRead; mutex2.WaitOne(); numRead2 = SerialPort.Read(buffer2, 0, numToRead2); mutex2.ReleaseMutex(); writeToBuffer1 = true; PlotData(buffer2, numRead2); } } </code></pre> <p>Your PlotData method will also need access to mutex1 and mutex2. Surround the code where you read the bytes with the WaitOne and ReleaseMutex methods. You will also need to learn how to write a thread-safe call to your plot data method so it can be called by a thread other than the one it was created on. <a href="https://stackoverflow.com/questions/6184/how-do-i-make-event-callbacks-into-my-win-forms-thread-safe">Thread-safe method</a></p>
    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.
    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