假设我有一个非常简单的带有IsIndeterminate=true
:的ProgressBar
<Window x:Class="My.Controls.IndeterminateProgressDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Window"
Width="300" Height="110" ResizeMode="NoResize" Topmost="True"
WindowStartupLocation="CenterScreen" WindowStyle="None">
<Grid>
<ProgressBar Width="200" Height="20" IsIndeterminate="True" />
</Grid>
</Window>
我想在可能需要一段时间的任务期间显示此对话框。我不在乎进度(我无法确定),我只想通知用户我做了一些可能需要几秒钟的事情。
public void GetResult()
{
string result = DoWhileShowingDialogAsync().Result;
//...
}
private async Task<string> DoWhileShowingDialogAsync()
{
var pd = new IndeterminateProgressDialog();
pd.Show();
string ret = await Task.Run(() => DoSomethingComplex()));
pd.Close();
return ret;
}
然而,UI只是无限冻结,任务似乎永远不会返回。问题不在DoSomethingComplex()中,如果我同步运行它,它就可以顺利完成。我很确定这是因为我误解了wait/async,有人能给我指明正确的方向吗?
.Result
这是一个典型的UI线程死锁。使用wait。在呼叫树上一直使用它。
为了澄清起见,"在调用树上一直使用它"意味着您需要从UI线程调用它。类似这样的东西:
private Task<string> DoWhileShowingDialogAsync()
{
return Task.Run(() => DoSomethingComplex());
}
private string DoSomethingComplex()
{
// wait a noticeable time
for (int i = 0; i != 1000000000; ++i)
; // do nothing, just wait
}
private async void GetResult()
{
pd.Show();
string result = await DoWhileShowingDialogAsync();
pd.Close();
}