簡體   English   中英

在長時間運行的任務中顯示自定義對話框窗口

[英]Displaying a custom dialog window during a long-running task

假設我有一個非常簡單的帶有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只會無限死機,並且Task似乎永遠不會返回。 問題不出在DoSomethingComplex()內,如果我同步運行它就可以毫無問題地完成。 我很確定這是因為我在使用await / async時誤解了某些內容,有人可以指出我正確的方向嗎?

.Result

這是經典的UI線程死鎖。 使用等待。 在調用樹中一直使用它。

只是為了澄清,“在調用樹中一直使用它”意味着您需要從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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM