0

I am writing a UWP background app to run on a Raspberry Pi using VS2017 templates for IoT. The app will listen for data from an Arduino on it's serial port so I need to access async methods.

The only way I can get the code to compile is to make the return type of my async "Listen()" method void, but as I can't await the call to Listen() in the Run() method it blocks up when it reaches FromIdAsync();

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        // Create the deferral by requesting it from the task instance.
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        ListenAsync();
        deferral.Complete();
    }

    private async void ListenAsync()
    {
        // some more code.....
        serialPort = await SerialDevice.FromIdAsync(deviceID);
    }

When trying to make the return type Task, or Task<T> I get the compiler error:

    Severity    Code    Description Project File    Line    Suppression State
Error       Method 'RMSMPBackgroundApp.StartupTask.ListenAsync()' has a parameter of type 'System.Threading.Tasks.Task' in its signature.  Although this type is not a valid Windows Runtime type, it implements interfaces that are valid Windows Runtime types.  Consider changing the method signature to use one of the following types instead: ''.    RMSMPBackgroundApp  C:\Users\Dan.Young\documents\visual studio 2017\Projects\RMSMPBackgroundApp\RMSMPBackgroundApp\StartupTask.cs   41

I have also tried to make the Listen() method private as some posts suggest.

I am relatively new to async programming so I must be missing something obvious?

Thanks.

Dan Young
  • 137
  • 1
  • 2
  • 12

1 Answers1

0

I ran into a similar situation and found out that we can use Task return type in the classes present in our background task . In order to do this we need to add a method that has a return type of IAsyncOperation<YourCustomClass> which will call your existing method with Task<YourCustomClass> .:

public IAsyncOperation<YourCustomClass> getDataAsync()
{
    return LoadPositionDataAsync().AsAsyncOperation();
    //where LoadPositionDataAsync() has a return type of Task<YourCustomClass>
}

From your Run() method you can call getDataAsync() to execute your code..

Pratyay
  • 1,291
  • 14
  • 23
  • Thanks, however this is not working for me. I still get the error that Task is not a valid Windows Runtime Type. Could you provide the whole piece of code inclusing the run method and 'using' statements so I can see if I am missing something? Thanks. – Dan Young Aug 25 '17 at 14:36