简体   繁体   中英

Displaying a custom dialog window during a long-running task

Let's say I have a very simple ProgressBar with IsIndeterminate=true :

<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>

I want to show this dialog during a Task that may take a while. I don't care about progress (I can't determine it), I just want to inform the user that I do something that may take some seconds.

 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;
}

However the UI just freezes infinitely and the Task seems to never return. The problem doesn't lie within DoSomethingComplex(), it completes without issues if I run it synchronously. I'm pretty sure it's because I misunderstood something with await/async, can someone point me in the right direction?

.Result

That's a classic UI thread deadlock. Use await. Use it all the way up the call tree.

Just for some clarification, 'use it all the way up the call tree' means you need to call it from the UI thread. Something like this:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM