首页 文章

UWP后台应用程序中的异步调用

提问于
浏览
0

我正在编写一个UWP后台应用程序,使用VS2017模板在Raspberry Pi上运行物联网 . 该应用程序将在其串口上侦听来自Arduino的数据,因此我需要访问异步方法 .

我可以获得编译代码的唯一方法是使我的异步“Listen()”方法的返回类型为void,但由于我无法在Run()方法中等待对Listen()的调用,因此它会阻塞它到达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);
    }

当尝试返回类型 Task, or Task<T> 时,我收到编译器错误:

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

我也尝试将Listen()方法设为私有,如某些帖子所示 .

我对异步编程比较新,所以我必须遗漏一些明显的东西?

谢谢 .

1 回答

  • 0

    我遇到了类似的情况,发现我们可以在后台任务中的类中使用Task返回类型 . 为此,我们需要添加一个返回类型为 IAsyncOperation<YourCustomClass> 的方法,该方法将使用 Task<YourCustomClass> 调用现有方法 . :

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

    Run() 方法中,您可以调用 getDataAsync() 来执行您的代码 .

相关问题