user690069
user690069

Reputation: 338

my Gridview still freezes in backgroundworker Dowork while using this.invoke(MethodInvoker)delegate

I want to update my gridview gradually while retrieving data

I've a backgroundworker Do work function as follows

    private void backGroundWrkr_DoWork(object sender, DoWorkEventArgs e)
    {
        DataTable dtInstant = new DataTable();

        for (int i = 0; i < allFiles.Count; i++)
        {
            if (backGroundWrkr.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

               myApp.processFile(allFiles[i]);


              this.Invoke((MethodInvoker)delegate
              {
               myGrdVw.DataSource = myApp.dtResults;
              });


            backGroundWrkr.ReportProgress(100 * (i + 1) / allFiles.Count);
        }
        backGroundWrkr.ReportProgress(100);

    }

and this is my Report Progress function

 private void backGroundWrkr_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;

        }

and this is my backGroundWrkr complete

private void backGroundWrkr_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar.Visible = false;
            allFiles.Clear();
        }

I've tried also BeginInvoke instead of Invoke and still my gridview freezes! My logic of proccessing files has no problem because in case I put datagridview binding in workercomplete it binds successfully

Upvotes: 1

Views: 346

Answers (2)

user690069
user690069

Reputation: 338

After 2 days of search and unsuccessful trials I've solved it as follows While binding it seems that the backgroundworker is working in the datatable so I bind a copy of the results datatable and it solves my problem

private void backGroundWrkr_DoWork(object sender, DoWorkEventArgs e)
{
    DataTable dtInstant = new DataTable();

    for (int i = 0; i < allFiles.Count; i++)
    {
        if (backGroundWrkr.CancellationPending)
        {
            e.Cancel = true;
            return;
        }

           myApp.processFile(allFiles[i]);


          this.Invoke((MethodInvoker)delegate
          {
           myGrdVw.DataSource = myApp.dtResults.copy();
          });


        backGroundWrkr.ReportProgress(100 * (i + 1) / allFiles.Count);
    }
    backGroundWrkr.ReportProgress(100);

}

Thanks all for your help!

Upvotes: 1

Graffito
Graffito

Reputation: 1718

Try to bind the datasource only once (i.e. before calling DoWork) and execute myGrdVw.Invalidate() in backGroundWrkr_ProgressChanged.

Upvotes: 0

Related Questions