Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 324467
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T09:07:36+00:00 2026-05-12T09:07:36+00:00

Let’s say I want to have a function which reads data from the SerialPort

  • 0

Let’s say I want to have a function which reads data from the SerialPort
and returns a byte[].

public byte[] RequestData(byte[] data)
{
    //See code below
}

Something as simple as this really doesn’t work/perform well and isn’t very reliable:

byte[] response = new byte[port.ReadBufferSize];

port.Open();    
port.Write(data, 0, data.Length);

Thread.Sleep(300); //Without this it doesn't even work at all

Console.WriteLine("Bytes to read: {0}", port.BytesToRead);

int count = port.Read(response, 0, port.ReadBufferSize);

Console.WriteLine("Read {0} bytes", count);

port.Close();
port.Dispose();       

return response.GetSubByteArray(0, count);

I also tried replacing the Thread.Sleep with something like:

while (port.BytesToRead < 14)
{
    //Maybe Thread.Sleep(10) here?
}

But that causes problems to. (PS: I know I need at least 14 bytes)

Of course a better way (I think) would be to have something like:

port.ReceivedBytesThreshold = 14;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();

port.Write(data, 0, data.Length);

And then having a handler of course:

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    var port = (SerialPort)sender;

    while (port.BytesToRead > 0)
    {
        //Read the data here
    }
}

But then I can’t return the data as the result of the function I wanted to define?
The client code using this would have to subscribe to an event raised by this code,
but then how would it know the response is really the response to the request it just made.

(Multiple messages might be sent, and I can imagine one message taking longer to process on the other side than the other, or something).

Any advise would be welcome

UPDATE

The following code works a lot better, but if I remove the Thread.Sleep() statements it once again stops working properly. For example, the serial port monitoring tool clearly indicates 17 bytes have been written on the serial line. The first time BytesToRead = 10 and the next time BytesToRead = 4 , but then BytesToRead remains 0 so where did the last 3 bytes go to ?

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Thread.Sleep(100);
    while (port.BytesToRead > 0)
    {
        Console.WriteLine("Bytes to read: {0}", port.BytesToRead);
        var count = port.BytesToRead;

        byte[] buffer = new byte[count];

        var read = port.Read(buffer, 0, count);

        if (count != read)
            Console.WriteLine("Count <> Read : {0} {1}", count, read);

        var collectAction = new Action(() =>
        {
            var response = dataCollector.Collect(buffer);

            if (response != null)
            {
                this.OnDataReceived(response);
            }
        });

        collectAction.BeginInvoke(null, null);
        Thread.Sleep(100);
    }    
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T09:07:36+00:00Added an answer on May 12, 2026 at 9:07 am

    Problem solved:

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        var count = port.BytesToRead;
        byte[] buffer = new byte[count];
        var read = port.Read(buffer, 0, count);
    
        var response = dataCollector.Collect(buffer);
    
        if (response != null)
        {
            this.OnDataReceived(response);
        }            
    }
    

    It seems the problem wasn’t actually this code but the code in the dataCollector.Collect() method.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 192k
  • Answers 192k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Why not just create a database or each company? And… May 12, 2026 at 6:22 pm
  • Editorial Team
    Editorial Team added an answer Windows Installer XML It will be available as part of… May 12, 2026 at 6:22 pm
  • Editorial Team
    Editorial Team added an answer You can configure maven-surefire-plugin. For example: <project> <build> <plugins> <plugin>… May 12, 2026 at 6:22 pm

Related Questions

I have a French site that I want to parse, but am running into
Let's say you create a wizard in an HTML form. One button goes back,
Let's say I'm building a data access layer for an application. Typically I have
Let's say you have a class called Customer, which contains the following fields: UserName
Let me try to explain what I need. I have a server that is

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.