BackgroundWorker to read database and update GUI

前端 未结 1 1708
不知归路
不知归路 2021-01-17 08:18

I am trying to keep my indeterminate ProgressBar animation running smoothly as I query database and updating DataGrid in DoWork

相关标签:
1条回答
  • 2021-01-17 08:27

    Create a collection of items in your DoWork event handler and then set the ItemsSource property of the DataGrid to this one in the RunWorkerCompleted event handler once you are done fetching the data on a background thread:

    private void btnSearch_Click(object sendoer, RoutedEventArgs e)
    {
        bgw.WorkerReportsProgress = true;
        bgw.ProgressChanged += ProgressChanged;
        bgw.DoWork += DoWork;
        bgw.RunWorkerCompleted += BGW_RunWorkerCompleted;
    
        myProgressBar.Visibility = Visibility.Visible;
        bgw.RunWorkerAsync();
    }
    
    private void DoWork(object sender, DoWorkEventArgs e)
    {
        List<object> results = new List<object>();
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM " + MyTableName, conn))
            {
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        results.Add(new
                        {
                            Id = rdr.GetInt32(0),
                            Name = rdr.GetString(1).ToString(),
                        });
                    }
                }
            }
        }
    
        e.Result = results;
    }
    
    private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        myDataGrid.ItemsSource = e.Result as List<object>;
        myProgressBar.Visibility = Visibility.Collapsed;
    }
    

    You need to call the ReportProgress method of the BackgroundWorker for any progress to be reported but it is pretty meaningless to report progress from a database retrieval operation since you have no clue about the actual progress anyway. You'd better just use an indeterminate ProgressBar and show it when you start the operation and hiding it when the operation has completed as demonstrated in the sample code above.

    And Thread.Sleep will block the current thread. If you block the UI thread, your UI, including your ProgressBar, cannot be updated so you don't want to do this.

    0 讨论(0)
提交回复
热议问题