编程语言
首页 > 编程语言> > c#-通过分派器的Action(()=> {})冻结ui

c#-通过分派器的Action(()=> {})冻结ui

作者:互联网

我尝试了一个简单的async-await示例,其中包含和不包含.ConfigureAwait(false).
使用.ConfigureAwait(false),您可以通过分派器更新ui,不需要它就不需要它.
这是下面代码中的情况1和3-有效,我可以理解它是如何工作的.

我的问题是关于案例2,其中我添加了-完全不需要-刷新
通过调度程序执行Action(()=> {}).
这偶尔会冻结我的用户界面.尤其是在反复调用事件处理程序之后.
有人可以解释为什么在情况2中ui冻结吗?

private void Test_Click(object sender, RoutedEventArgs e)
{
    Test();
}

public async void Test()
{
    Print("Start task");

    // Case 1 & 2
    await Task.Delay(2000);
    // Case 3
    await Task.Delay(2000).ConfigureAwait(false);

    Print("Finished task");
}

void Print(string text)
{
    // Case 1 & 2
    Output.Inlines.Add(new Run(text) { Foreground = Brushes.Blue, FontWeight = FontWeights.Bold });
    // Case 2 only
    Output.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { }));

    // Case 3
    Output.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, 
       new Action(() => 
       {  
         Output.Inlines.Add(new Run(text) { Foreground = Brushes.Blue, FontWeight = FontWeights.Bold 
       }); }));
}

解决方法:

这是WPF中的错误.

它运行一个经过筛选的GetMessage()循环(请参阅here),如果循环是停留在队列中不符合过滤器的消息,则返回will hang.

标签:async-await,c
来源: https://codeday.me/bug/20191121/2050072.html