【发布时间】:2017-05-30 03:46:45
【问题描述】:
我正在尝试按照this example on Micr*soft's blog 上的步骤创建 Windows 通知的侦听器
据说获得用户授权的第二个代码片段没有编译:
error CS4033: The 'await' operator can only be used within an async method.
Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
虽然我不熟悉C#的async/await机制,但是问题的方法叫RequestAccessAsync,Visual Studio打开的源码在方法上方有一个[RemoteAsync]。
这是完整的代码片段:
// Get the listener
UserNotificationListener listener = UserNotificationListener.Current;
// And request access to the user's notifications (must be called from UI thread)
UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync();
switch (accessStatus)
{
// This means the user has granted access.
case UserNotificationListenerAccessStatus.Allowed:
// Yay! Proceed as normal
break;
// This means the user has denied access.
// Any further calls to RequestAccessAsync will instantly
// return Denied. The user must go to the Windows settings
// and manually allow access.
case UserNotificationListenerAccessStatus.Denied:
// Show UI explaining that listener features will not
// work until user allows access.
break;
// This means the user closed the prompt without
// selecting either allow or deny. Further calls to
// RequestAccessAsync will show the dialog again.
case UserNotificationListenerAccessStatus.Unspecified:
// Show UI that allows the user to bring up the prompt again
break;
}
我该如何解决这个问题?
【问题讨论】:
-
你的方法签名在哪里?你把它标记为
async了吗? -
您需要展示更多代码,您需要展示保存您的代码示例的方法,
-
谢谢大家,这就是问题所在。这段代码在一个类构造函数中,(正如我刚刚学到的,不能是异步的)
-
@RSFalcon7 查看我更新的答案,以解决在构造函数中运行异步代码的解决方法。
标签: c# uwp async-await