[英]Async Task Still Blocking UI Thread
I'm reallt trying to get my head around async/await
and Tasks
. 我正在努力使我的头脑避开
async/await
和Tasks
。 I'm trying to get one method down so that I can use it throughout my program. 我试图降低一种方法,以便可以在整个程序中使用它。 Basically I have my own version of
BusyIndicator
that I want to display whilst work is being done. 基本上,我有自己的
BusyIndicator
版本,要在工作完成时显示。 Here is a basic example; 这是一个基本示例;
private async void OnPageLoad(object sender, RoutedEventArgs e)
{
var waitWindow = new PleaseWaitWindow();
waitWindow.Show();
await LoadCompanyContracts();
waitWindow.Close();
}
private async Task LoadCompanyContracts()
{
await Task.Run(() =>
{
Dispatcher.Invoke(() =>
{
//Work done here
});
});
}
Even through these two methods and attempting implementing Tasks
my BusyIndicator
still doesn't rotate, it is displayed but is frozen so in effect I believe the UI thread is still blocked. 即使通过这两种方法并尝试实现“
Tasks
我的BusyIndicator
仍然不会旋转,它会显示但被冻结,因此实际上我认为UI线程仍然被阻止。 How can I modify this piece of code to ensure that all CPU bound work is not blocking the UI thread? 如何修改这段代码,以确保所有与CPU绑定的工作都不会阻塞UI线程?
As a general rule, you shouldn't use Dispatcher
at all. 通常,您根本不应该使用
Dispatcher
。 It's extremely common practice, but it's a commonly bad practice. 这是非常常见的做法,但通常是不好的做法。
private async Task LoadCompanyContracts()
{
await Task.Run(() =>
{
//Work done here
});
// Update UI if necessary.
}
Don't do you work inside Dispatcher.Invoke() , because your dispatcher is associated with ui thread. 不要在Dispatcher.Invoke()内部工作,因为调度程序与ui线程关联。 Do your work inside Task and use dispatcher only for updating UI
在Task内完成工作,并仅使用调度程序更新UI
private async Task LoadCompanyContracts()
{
await Task.Run(() =>
{
/*Work done here
*
*/
Dispatcher.Invoke(() =>
{
//Update UI
});
});
}
After looking for some examples in my code here a solution you can try : 在这里找到我的代码中的一些示例后,可以尝试以下解决方案:
private async void OnPageLoad(object sender, RoutedEventArgs e)
{
var waitWindow = new PleaseWaitWindow();
waitWindow.Show();
InitLoadCompanyContracts();
waitWindow.Close();
}
private async void InitLoadCompanyContracts(){
await LoadCompanyContracts();
}
private async Task LoadCompanyContracts()
{
await Task.Run(() =>
{
Dispatcher.Invoke(() =>
{
//Work done here
});
});
}
I use this to have an awaitable method but out of all "graphics" methods. 我使用此方法有一个值得期待的方法,但是没有所有“图形”方法。 I don't know if is the best way to do that, but for me it's work.
我不知道这样做是否是最好的方法,但是对我来说这是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.