【发布时间】:2016-11-03 11:49:17
【问题描述】:
我刚开始使用我的新 Raspberry Pi 3 和 Win10 IOT。
我尝试了一个小项目,但在 async/await 语句方面遇到了一些问题。
我不是 C# 新手,也不是 await/async 新手,但这是我第一次使用 UWP,所以我可能会错过这个平台与 WinForms/WPF 环境相比的一些技巧。
(仅供参考,我暂时没有接触到Win10开发机,所以下面的sn-ps可能无法立即编译)
这是 Rpi 上无头应用程序的标准模板:
public async void Run(IBackgroundTaskInstance taskInstance)
{
taskInstance.GetDeferral();
await DoSomethingAsync();
// Other irrevelant stuff then...
defferal.Complete();
}
然后是异步方法:
private async Task DoSomethingAsync()
{
// Something done async
await Task.Delay(1000);
} // <--- Hangs here
将应用部署到树莓派时,进入DoSomethingAsync方法,执行其内容没有问题。
我的问题是应用程序在退出的分号处挂起。
我们需要使用CoreDispatcher、ThreadPool,还是简单的new TaskFactory().StartNew(async () => { await DoSomethingAsync(); });?
我不明白的是,使用 await/async 应该在另一个线程上执行我的方法,但它挂起的方式与等待 UI 处理消息队列的方式相同(此处为 WinForms/WPF 背景: ) )
提前谢谢你。
编辑:如果我删除所有异步内容以使其同步运行,则此 sn-p 有效。
【问题讨论】:
-
你是什么意思“挂起”和什么退出分号?顺便说一句,您不需要提供任何额外的东西。在任何情况下,
await等待异步方法的完成,它不会自动使某些东西异步 -
What I don't understand is the use of the await/async should execute my method on an other thread如果您需要在另一个线程上完成工作,则不应使用await。await将等待通话结束。 -
@PanagiotisKanavos,我编辑了我的问题,并评论了它挂在哪个右括号上。我所说的挂起是指当我一步一步地做一些事情时,它不会走得更远。
-
@jackjop
await将等待调用完成,但由于方法是async,因此执行与“主线程”异步运行,因此不应阻塞任何它。 -
这在 Windows 10 Destktop 上似乎不是问题。
标签: c# async-await uwp iot raspberry-pi3