My application works with some peripheral device. I must receive array of bytes from COM-port. Below are the snippets of code executing synchronously from my application:
// COM-port used.
private SerialPort _serialPort;
// Buffer for bytes received from COM-port.
private Byte[] _inputOutputBuffer;
// Buffer for instances of Point.
private List<Point> _linePoints = new List<Point>();
This method prepairs COM-port to work.
// Prepaires COM-port.
void PrepareComPort()
{
if (this._serialPort == null)
this._serialPort = new SerialPort(this.SelectedAvailableComPortsName);
this._serialPort.BaudRate = 115200;
this._serialPort.Parity = Parity.None;
this._serialPort.DataBits = 8;
this._serialPort.StopBits = StopBits.One;
this._serialPort.Handshake = Handshake.None;
this._serialPort.ReadTimeout = SerialPort.InfiniteTimeout
this._serialPort.WriteTimeout = 1000;
if (!this._serialPort.IsOpen)
this._serialPort.Open();
}
This method gets array of bytes via COM-port.
// Gets bytes from device via COM-port.
void recieveBytesFromDevice()
{
// Get bytes array at whole from COM-port.
while (this._serialPort.BytesToRead < 4006) { ; }
this._inputOutputBuffer = new Byte[this._serialPort.BytesToRead];
this._serialPort.Read(this._inputOutputBuffer, offset: 0, count: this._serialPort.BytesToRead);
}
This method fills the list of instances of Point.
// Fills list of instances of Point.
void FillPointsList()
{
for (int i = 0, j = 0; i <= this._inputOutputBuffer.Length - 8; i++)
{
Int16 shortValue = 0;
if (i % 2 == 0)
{
Byte[] bytes = new Byte[] { this._inputOutputBuffer[i], this._inputOutputBuffer[i + 1] };
Array.Reverse(bytes);
shortValue = BitConverter.ToInt16(bytes, startIndex: 0);
_linePoints.Add(new Point(j, shortValue));
j++;
}
}
}
My application sends data request via COM-port to the peripheral device and the peripheral device always send just 4006 bytes as a reply which my application must receive. If the peripheral device sends 4006 bytes without any delay than the application works good. But when the peripheral device has some delay before sending of 4006 bytes than my application hangs. How to realize aforementioned PrepareComPort and FillPointsList methods as one method for asynchronous work using await async?