Search code examples
c#uwptimeoutuart

Async Timeout UWP


Reference thread, accepted answer Asynchronously wait for Task to complete with timeout

My method UART_receive() returns a string. How do I get the string out of the timeout task?
Right now it obviously doesn't work. Without the timeout task my serial communication works fine.

using System;
using Windows.Storage.Streams;              //Uart Seriell
using Windows.Devices.Enumeration;          //UART Seriell
using Windows.Devices.SerialCommunication;  //UART Seriell

public MainPage()
{
    this.InitializeComponent();

    Serial();
}

public async void Serial()
{
    //configure serial setting
    //configure serial setting

    while (true)
    {
        UART_send("+");

        //receive
        int timeout = 1000;
        var task1 = UART_receive();

        if (await Task.WhenAny(task1, Task.Delay(timeout)) == task1)
        {
            statusbar_main.Text = "ok";
        }
        else
        {
            statusbar_main.Text = "not ok";
        }
        string rxBuffer = Convert.ToString(task1);
    }
}

private async Task<string> UART_receive()
{
    const uint maxReadLength = 13;

    uint bytesToRead = await dataReader.LoadAsync(maxReadLength);
    string rxBuffer = dataReader.ReadString(bytesToRead);

    return rxBuffer;
}

Solution

  • How do I get the string out of the timeout task?

    string rxBuffer = await task1