此问题已经在这里有了答案:
我的函数可以读取和发送串行字符串。读写处于while循环中。现在,代码停止在等待dataReader.LoadAsync,直到收到串行消息。我该如何为此超时?例如。如果500毫秒后仍未收到任何消息,请取消等待dataReader.LoadAsync并完成循环。
我尝试了cancallationtokens,但没有成功。
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
[尝试以下操作时出现错误。-maxReadLenght进入任务而不是bytesToRead。-等待任务时出现错误“ uint不包含GetWaiter的定义”-CancellationToken无效
//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);