加载数据时,ProgressBar不是动画;并且在使用await时加载不等待

时间:2015-03-06 18:37:29

标签: c# wpf animation progress-bar async-await

在我的app中,需要从数据库加载数据。在此期间,会显示正在显示的启动画面。我想有一个进度条动画,所以将其添加到启动屏幕xaml;

<ProgressBar Margin="5" DockPanel.Dock="Top" IsIndeterminate="True"  />

这可行,但动画基本上会在每次长时间检索数据时停止。我的加载数据看起来像这样;

private void loadData()
{
    getData1FromDB();
    displayData1_OnScreen();
    getData2FromDB();
    displayData2_OnScreen();
    getData3FromDB();
    displayData3_OnScreen();
}

因此,当getData1FromDB()正在运行时,进度条动画将停止。想象问题可以解决;

private async void loadData()
{
   await Task.Run(() => getData1FromDB());
   displayData1_OnScreen();
   getData2FromDB();
   await Task.Run(() => displayData2_OnScreen());
   getData3FromDB();
   await Task.Run(() => displayData3_OnScreen());
}

这引起了另一个问题。当getData1FromDB()正在运行时,程序进入displayData1_OnScreen。由于未getData1FromDB()未完成,因此未显示任何数据。

如何在不重写整个加载程序的情况下解决这个问题?

编辑:根据评论;

没有其他人在呼叫displayData1_OnScreen,说实话我也很惊讶。我唯一能想到的是从构造函数中调用loadData()

说实话,不,我不确定这是问题所在。我试图在@BradleyDotNET提出它之后进行更多调试以查看实际发生的情况。

关于getData1FromDB的问题,有点难以突破。基本上它根据参数集构建一个sqlCMD字符串,然后像这样运行它;

    DataTable dt = new DataTable();
string ConString = ConnectionString();
using (MySqlConnection con = new MySqlConnection(ConString))
{
    MySqlDataAdapter da = new MySqlDataAdapter();
    MySqlCommand cmd = new MySqlCommand(sqlCMD, con);
    con.Open();
    da.SelectCommand = cmd;
    da.Fill(dt);
    con.Close();
}
return dt;

2 个答案:

答案 0 :(得分:1)

对于它的价值,即使loadData()在构造函数中运行,以下repro尝试似乎也能做你想要的 -

CS:

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace WpfAsyncAwaitProgressbar
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new TestViewModel();
        }
    }

    public class TestViewModel : INotifyPropertyChanged
    {
        public TestViewModel()
        {
            Text1 = Text2 = Text3 = "Loading ...";
            loadData();
        }

        public string Text1 { get; private set; }
        public string Text2 { get; private set; }
        public string Text3 { get; private set; }

        public Visibility ProgressbarVisibility { get; private set; }

        private async void loadData()
        {
            setBusyMode(true);
            await Task.Run(() => getData1FromDB());
            await Task.Run(() => getData2FromDB());
            await Task.Run(() => getData3FromDB());
            setBusyMode(false);
        }

        private void getData1FromDB()
        {
            Thread.Sleep(3000);
            Text1 = "Data Result 1";
            raisePropertyChanged(() => Text1);
        }

        private void getData2FromDB()
        {
            Thread.Sleep(2000);
            Text2 = "Data Result 2";
            raisePropertyChanged(() => Text2);
        }

        private void getData3FromDB()
        {
            Thread.Sleep(1000);
            Text3 = "Data Result 3";
            raisePropertyChanged(() => Text3);
        }

        private void setBusyMode(bool isBusy)
        {
            ProgressbarVisibility = isBusy ? Visibility.Visible : Visibility.Hidden;
            raisePropertyChanged(() => ProgressbarVisibility);
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected void raisePropertyChanged<TProperty>(Expression<Func<TProperty>> projection)
        {
            var memberExpression = (MemberExpression)projection.Body;
            raisePropertyChanged(memberExpression.Member.Name);
        }

        private void raisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion INotifyPropertyChanged
    }
}

XAML:

<Window x:Class="WpfAsyncAwaitProgressbar.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" SizeToContent="WidthAndHeight">
    <StackPanel>
        <TextBlock Text="{Binding Text1}"/>
        <TextBlock Text="{Binding Text2}"/>
        <TextBlock Text="{Binding Text3}"/>
        <ProgressBar Visibility="{Binding ProgressbarVisibility}"
                     IsIndeterminate="True"
                     Height="10"/>
    </StackPanel>
</Window>

答案 1 :(得分:-1)

  1. 除了事件处理程序外,您不应该使用async void:http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-1-Async-void-is-for-top-level-event-handlers-only

  2. wpf中有动画,即使在UI线程被阻止的情况下也可以在图形卡上运行,但是它们非常有限,而且我很依赖它们

  3. 这段代码怎么样?

    private async Task loadData()
    {
       await Task.Run(getData1FromDB);
       displayData1_OnScreen();
    
       await Task.Run(getData2FromDB);
       displayData2_OnScreen();
    
       await Task.Run(getData3FromDB);
       displayData3_OnScreen();
    }