My function can read and send serial strings.
Read and write is in a while loop.
Right now the code stops at await dataReader.LoadAsync until a serial essage is received.
How do I make a timeout for this?
E.g. if nothing is received after 500ms, cancel await dataReader.LoadAsync and finish the loop.
I experimented with cancallationtokens, but without any success.
public async void Serial()
{
//configure serial setting
//configure serial setting
//configure serial setting
//configure serial setting
// Seriell while
while (true)
{
//send
dataWriter.WriteString(txBuffer);
bytesWritten = await SerialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());
textblock_DebugTx_live.Text = txBuffer; //Ausgabe Debug Tx Senden
//receive
uint bytesToRead = await dataReader.LoadAsync(maxReadLength);
string rxBuffer = dataReader.ReadString(bytesToRead);
textblock_DebugRx_Gas_live.Text = rxBuffer; //Ausgabe Wert Alkoholsensor
} //Seriell while
} //Seriell
When I try the follow, I get errors.
- maxReadLenght goes into task and not to bytesToRead.
- error at await task "uint contains no definition for GetWaiter"
- CancellationToken is invalid
//receive
uint bytesToRead;
int timeout = 1000;
var task = await dataReader.LoadAsync(maxReadLength);
if (await Task.WhenAny(task, Task.Delay(timeout, CancellationToken)) == task)
{
// Task completed within timeout.
// Consider that the task may have faulted or been canceled.
// We re-await the task so that any exceptions/cancellation is rethrown.
await task;
}
else
{
// timeout/cancellation logic
}
string rxBuffer = dataReader.ReadString(bytesToRead);