【发布时间】:2014-05-21 06:54:38
【问题描述】:
我正在制作一个 Windows 8.1 平板电脑应用程序,并且大量使用 async 关键字。 我对 async 关键字的理解是,虽然它对程序员来说似乎是同步的,但不能保证当你的 await 完成时你会在同一个线程上运行。
在我的代码隐藏文件中,我使用 Dispatcher 在 UI 线程上运行任何 UI 更新。我发现的每个示例都表明,在使用“回调”类型场景时这是一个很好的做法,但在使用异步时我没有看到任何提及。根据我对异步的理解,每当我想在任何 await 调用之后更新 UI 时,我似乎都需要使用调度程序。
我试图通过将我的理解写在下面的代码中来更清楚。
private void SomeEventHandler(object sender, RoutedEventArgs e)
{
UpdateUI(); //This should run in my UI thread
await Foo(); //When Foo returns I have no guarantee that I am in the same thread
UpdateUI(); //This could potentially give me an error
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
UpdateUI(); //This will run in the UI thread
});
}
我是否只需要访问 UIContext 而线程无关紧要?如果有人能为我澄清这一点,那就太好了。
【问题讨论】:
标签: c# multithreading xaml asynchronous async-await