private async Task<byte[]> ReadAsync(int timeout, CancellationToken cancellationToken)
{
try
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1024;
// If task cancellation was requested, comply
//cancellationToken.ThrowIfCancellationRequested();
if (dataReaderObject == null)
dataReaderObject = new DataReader(serialPort.InputStream);
// Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
dataReaderObject.InputStreamOptions = InputStreamOptions.ReadAhead;
// set serial timeout for reading. initialize the timout reading function
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(timeout);
//await Task.Delay(timeout);
// Create a task object to wait for data on the serialPort.InputStream
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
// Launch the task and wait
UInt32 bytesRead = await loadAsyncTask;
byte[] retval = null;
if (bytesRead > 0)
{
retval = new byte[bytesRead];
dataReaderObject.ReadBytes(retval); //return the bytes read
//Debug.WriteLine(String.Format("Bytes received successfully: {0}", bytesRead));
}
else
Debug.WriteLine(String.Format("No bytes received successfully"));
return retval;
}
catch (Exception)
{
// Cleanup once complete
if (dataReaderObject != null)
{
dataReaderObject.DetachStream();
dataReaderObject = null;
}
Debug.WriteLine("Exception in reading");
return null;
}
}