0
votes

I have this piece of code:

public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {   
            int bytes = serial.BytesToRead;
            byte[] buffer = new byte[bytes];
            serial.Read(buffer, 0, bytes);
            foreach (var item in buffer)
            {
                Console.Write(item.ToString());
            }
            Variables.buffering = BitConverter.ToInt64(buffer, 0);
            Console.WriteLine();
            Console.WriteLine(Variables.buffering);
            Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
            thread.Start();
            thread.Join();

        }

then I will send 13 bytes to the serial port. How will I modify this so that my program will wait for the buffer to become 13 bytes and if the buffer is 13 bytes, it should execute this one without an error:

Variables.buffering = BitConverter.ToInt64(buffer, 0);

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll 

Additional information: Destination array is not long enough to copy all the items in the collection. Check array index and length.
1
If BytesToRead is < 13, don't read from the serial port. If there is, just read 13 bytes.Matt Burland
thanks. It helps alot. I did not get the error anymoreiaskyou

1 Answers

0
votes

You will receive the ArgumentException when the size of the byte array is less than 8.

The ToInt64 method is expecting a byte array which it can take at least 8 values from the starting index.

This is stated on the MSDN documentation for the method under the 'Exceptions' section.

An way to apply your 13 bytes test can be done as follows:

public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
      if (serial.BytesToRead >= 13)
      {            
        byte[] buffer = new byte[13];
        serial.Read(buffer, 0, 13);
        foreach (var item in buffer)
        {
          Console.Write(item.ToString());
        }
        Variables.buffering = BitConverter.ToInt64(buffer, 0);
        Console.WriteLine();
        Console.WriteLine(Variables.buffering);
        Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
        thread.Start();
        thread.Join();
      }
    }