在NDC 2012的“Lucian Wischik - Async Part 2 -- deep dive into the new language feature of VB/C#”中,向我介绍了Dispatcher.Yield
的推荐用法。有没有人有关于如何(以及为什么)在野外使用此调用的示例(和解释)?
答案 0 :(得分:4)
例如,如果您有一个长时间运行的任务,但仍需要更新您的UI,则可以使用Yield
。
Yield
使您能够保留当前线程上下文并允许其他代码在底层上下文中运行。
public async void MyButton_Click(object sender, RoutedEventArgs e)
{
for( int i=0; i < 10000; i++)
{
ProcessSomeStuff(i);
// await the Yield to ensure all waiting messages
// are processed before continuing
await Task.Yield();
}
}
在上面的示例中,您可以处理异步,但调用Yield
将允许UI线程上的事件也执行,