在 wpf 应用程序中打开视图时延迟

delay while opening view in wpf application

我们正在使用 WPF、material 设计和 MS-Access 2007 作为后端开发应用程序。现在我们面临打开单个视图时应用程序变慢的问题,该特定视图有 16 个组合填充。处理需要 7 秒,以下代码用于绑定组合框项目源

     List<ComboBind> values = new List<ComboBind>();
     try
     {
      using (var oleDbCommand = new OleDbCommand())
         {
             oleDbCommand.CommandText = query  ;
             oleDbCommand.Connection = Connection.con;
             var sql = query;
             var oleDbDataReader = oleDbCommand.ExecuteReader();
         while (oleDbDataReader.Read())
             {
                 ComboBind b = new ComboBind();
                  b.id = oleDbDataReader[0].ToString().ToInt();
                  b.name = oleDbDataReader[1].ToString();
                  values.Add(b);                   
             }                
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }

看起来您正试图在视图初始化期间在 UI 线程中加载数据,这就是问题的原因。要么在后台线程中加载数据,要么在打开视图之前加载数据。

在单独的任务中加载数据的简单代码片段:

    //Might be your view code behind or
    //ViewModel if you are using MVVM
    public class ViewCodeBehind
    {
        public List<ComboBind> ComboItems { get; set; }

        public void Initialize()
        {
            //start bacground task for data loading
            var comboQuery = "select *from data";
            Task.Run(() => LoadItems(comboQuery));
        }

        public void LoadItems(string query)
        {
            List<ComboBind> values = new List<ComboBind>();
            try
            {
                using (var oleDbCommand = new OleDbCommand())
                {
                    oleDbCommand.CommandText = query;
                    oleDbCommand.Connection = Connection.con;
                    var sql = query;
                    var oleDbDataReader = oleDbCommand.ExecuteReader();
                    while (oleDbDataReader.Read())
                    {
                        ComboBind b = new ComboBind();
                        b.id = oleDbDataReader[0].ToString().ToInt();
                        b.name = oleDbDataReader[1].ToString();
                        values.Add(b);
                    }
                }

                //use dispatcher to pass data back to UI thread
                System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
                    new Action(() =>
                    {
                        ComboItems = values;
                    }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }