有没有人在现场使用Dispatcher.Yield?

时间:2013-11-19 23:39:23

标签: wpf multithreading

在NDC 2012的“Lucian Wischik - Async Part 2 -- deep dive into the new language feature of VB/C#”中,向我介绍了Dispatcher.Yield的推荐用法。有没有人有关于如何(以及为什么)在野外使用此调用的示例(和解释)?

1 个答案:

答案 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线程上的事件也执行,