Search code examples
c#queueserial-portbufferbackgroundworker

C# How to place serial input data into a queue and de-que using a backgroundworker


I need to take incoming data from a serial port place the 'ReadExisting' string into a queue, and then de-que back into the user interface.

During the de-que process I will be formatting the incoming string to remove unwanted characters, add LineFeeds (there are no EOL characters in the incoming), etc. and post various parts of the string into several controls (listbox, textbox) for viewing.

This is as far as I have been able to get to create a string (RxString) from incoming data:

 private void serialPort1_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)     
 {         
 RxString = serialPort1.ReadExisting();         
 this.Invoke(new EventHandler(DisplayText));     
 } 

I am able to get the incoming data, but when I try to format it and display it some of the data that comes in gets lost or dropped or something and the text gets unreadable. If I don't format the text & send it straight to a listbox the data is all there, but not useable because of all the extra code characters.

I'd like to handle the (DisplayText) using a backgroundworker so the serial data can come in to a queue so as to not be lost while the backgroundworker handles placing the info on screen. Unless theres a better way.


Solution

  • I assume that the data comes one line at the time, so you could always use the Queue-class and use the method Enqueue to add the incoming data.

    And to get an item from the Background-worker, just use Dequeue

    Here's a link to the MSDN-article about the Queue-class

    http://msdn.microsoft.com/en-us/library/7977ey2c.aspx

    Example:

    private Queue<string> data = new Queue<string>();
    
    private void Rx_GetData(e)
    {
        var rxString = e.ReadExisting();
        data.Enqueue(rxString);   
    }
    
    private void BackgroundWorker_DoWork()
    {
        while(rxConn.IsConnected) // Haven't worked with serial connections, so I don't know the proper property here..
        {
            if(data.Count > 0)
            {
                var str = data.Dequeue();
                FormatString(str);
            }
            Thread.Sleep(10);
        }
    }