【发布时间】:2021-09-02 03:12:02
【问题描述】:
我试图防止在等待时冻结应用程序界面,所以我编写了这个函数,但它不起作用。
错误在哪里,我该如何解决?
async void buttonBlocking()
{
await Task.Run(() =>
{
if (irTryCounter % 3 == 0)
{
this.Dispatcher.Invoke(() =>
{
grdLogin.IsEnabled = false;
Thread.Sleep(10000);
grdLogin.IsEnabled = true;
});
}
});
}
【问题讨论】:
-
你也可以在 lambda 中使用
async/await来调用Task.Delay,但这很奇怪。使用计时器? -
this.Dispatcher.Invoke()将在 UI 线程的上下文中运行该代码,因此睡眠将停止 UI 线程。 -
还有related。
-
除了@MatthewWatson 的好评之外,请注意
Dispatcher.Invoke不仅会导致 UI 线程死锁,还会导致线程池线程死锁。因此,请考虑使用Dispatcher.BeginInvoke。当然你会想把Thread.Sleep移到别处
标签: c# multithreading xaml async-await