B
B
Blaine_Mono2017-04-14 11:52:58
C++ / C#
Blaine_Mono, 2017-04-14 11:52:58

Reading data from the com port hangs the program. How to make a handler run on a different thread?

It is required to read the data that the arduina sends to the com port in real time and immediately process it. Now it goes to the DataReceivedHandler which freezes the program interface when running.
How can I make it work in a separate thread?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DedKulibin, 2017-04-14
@DedKulibin

How to: Use a Background Worker:
https://msdn.microsoft.com/en-us/library/cc221403(...

P
Peter, 2017-04-14
@petermzg

You create a separate thread through Thread, and there create a blocking SerialPort
that will wait for data on port.Read. And parse received.
If you have a windowed application, then you can use SynchronizationContext and through it Post data to window controls.

D
Dmitry Makarov, 2017-04-14
@DmitryITWorksMakarov

maybe something like:

using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Windows.Forms;

namespace serialport_process
{
    class Program
    {
        class OutputForm : Form
        {
            public RichTextBox richTextBox {get ;private set;}

            public OutputForm()
            {
                WindowState = FormWindowState.Maximized;

                richTextBox = new RichTextBox 
                {
                    Dock = DockStyle.Fill
                };
            }
        }

        static Encoding ENCODING = Encoding.ASCII;
        const int BUFFER_SIZE = 4096;
        static byte[] buffer = new byte[BUFFER_SIZE];

        delegate void AppendText(string inText);

        static void Main(string[] args)
        {
            var form = new OutputForm();

            var task = new Task(() => 
            {
                var serialPort = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.Two);

                serialPort.DataReceived += (sender, e) =>
                {
                    var count = serialPort.BytesToRead;
                    while (count > 0)
                    {
                        var current_count = serialPort.Read(buffer, 0, count < BUFFER_SIZE ? count : BUFFER_SIZE);
                        var text = ENCODING.GetString(buffer, 0, current_count);
                        count -= current_count;

                        form.Invoke((AppendText)(txt => form.richTextBox.AppendText(txt)), text);
                    }
                };
                serialPort.Open();
                while (true) ;
            });

            form.Load += (sender, e) => task.Start();

            Application.Run(form);
        }
    }
}

I haven't tested it, but I would start with this...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question