【问题标题】:Async Calls in UWP Background ApplicationUWP 后台应用程序中的异步调用
【发布时间】:2018-02-03 12:35:38
【问题描述】:

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

我可以编译代码的唯一方法是使我的异步“Listen()”方法的返回类型无效,但是因为我不能等待 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() 方法设为私有。

我对异步编程比较陌生,所以我肯定遗漏了一些明显的东西?

谢谢。

【问题讨论】:

    标签: c# asynchronous uwp background-application


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,但这对我不起作用。我仍然收到任务不是有效的 Windows 运行时类型的错误。您能否提供包含运行方法和“使用”语句的整段代码,以便我查看是否遗漏了什么?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多