【发布时间】: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