BackgroundWorker Component, Need Help!

pasensyoso

Newcomer
Joined
Feb 21, 2009
Messages
2
Hi guys!

Can anyone will me to have a few understanding of BackgroundWorker? This is the first time that I want to use this control since I shift to vs2005.

Its like this, I have a sub procedure, GetData() and GetFiles()
Now I like it to run under the BackgroundWorker to prevent those hazy delay of displaying the the values inside my form.

I have done this functionality with the older ways of threading. i just want to experiment this new control in vs 2005.

Just need some enlightment.:cool:
 
The background worker has a DoWork event, put the code you want to ruin in the background in there. It also raises an event when it's complete so you know it has finished.
 
Here is a working example (using C#) that might help get the point across.

It is too long to post in one message, so it will be as follows:
  • Background Constructor
  • Background Worker
  • Background Progress Changed
  • Background Completed

I apologize for not customizing it so that it is generic and easy to understand, but maybe including all my code will give you some pointers on new things to try.

First: Background Constructor
Code:
void Fill_DataGridView(ZTreeParam tp) {
  using (BackgroundWorker worker = new BackgroundWorker()) {
    worker.WorkerReportsProgress = true;
    worker.WorkerSupportsCancellation = true;
    worker.DoWork += new DoWorkEventHandler(Worker_FillDataGrid);
    worker.ProgressChanged +=new ProgressChangedEventHandler(Worker_ProgressChanged);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_FillDataGridComplete);
    worker.RunWorkerAsync(tp);
    if (worker.IsBusy == true) {
      Cursor = Cursors.WaitCursor;
    }
  }
}
 
Second: Background Worker
Code:
void Worker_FillDataGrid(object sender, DoWorkEventArgs e) {
  BackgroundWorker worker = sender as BackgroundWorker;
  worker.ReportProgress(-1);
  if (e.Argument is ZTreeParam) {
    ZTreeParam tp = (ZTreeParam)e.Argument;
    using (SqlDataAdapter da = new SqlDataAdapter()) {
      if (tp.StoredProcedure.CommandType == CommandType.StoredProcedure) {
        da.SelectCommand = tp.StoredProcedure;
      } else if (tp.StoredProcedure.CommandType == CommandType.Text) {
        da.SelectCommand = tp.StoredProcedure;
      } else { // I added the "else if" line above. Does the line below ever still get called?
        da.SelectCommand.CommandText = tp.ThreadString; // disable this break point if so
      }
      try {
        if (Action == MainAction.Reports) {
          if (_ReportOpt[_nFilter1Key] == _LEAKSITES) {
            string strSummary = string.Empty;
            if ((tp.Extra != null) && (tp.Extra != string.Empty)) {
              strSummary = tp.StoredProcedure.CommandText;
              da.SelectCommand.CommandText = tp.Extra;
              using (DataTable table = new DataTable()) {
                da.Fill(table);
                tp.DataSet1.Tables.Add(table);
              }
            }
            if (strSummary != string.Empty) {
              da.SelectCommand.CommandText = strSummary;
            }
          }
        }
        using (DataTable table = new DataTable()) {
          da.Fill(table);
          tp.DataSet1.Tables.Add(table);
        }
      } catch (SqlException err) {
        Global.LogError("Reporter - Worker_FillDataGrid", err);
        e.Result = err;
        return;
      }
    }
    e.Result = tp;
  } else {
    e.Result = null;
  }
}
 
Third: Background Progress Changed
Code:
void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
  _parent.AuthenticationReset();
  ZThreadParam obj = null;
  _frmProgress.ProgressValue = e.ProgressPercentage;
  if (_frmProgress.ProgressValue == -1) {
    _frmProgress.ProgressString = string.Empty;
    _frmProgress.TimeLeftString = string.Empty;
  } else if (e.UserState != null) {
    if (e.UserState is ZThreadParam) {
      obj = (ZThreadParam)e.UserState;
      if ((_frmProgress == null) || (_frmProgress.Cancelled == true)) {
        BackgroundWorker worker = sender as BackgroundWorker;
        worker.CancelAsync();
        return;
      }
      _frmProgress.HeaderText = obj.ThreadString;
      UpdateStatusBar(obj.ThreadString);
    } else if (e.UserState is string) {
      UpdateStatusBar((string)e.UserState);
    }
    if (_frmProgress.TimeLeftString == "Calculating...") {
      _threadTime = DateTime.Now;
      _frmProgress.TimeLeftString = "Calculating.....";
    } else {
      TimeSpan span = (DateTime.Now - _threadTime);
      if (0 < span.TotalSeconds) {
        int count = obj.Count + 1;
        int num = obj.Total - count;
        double numPerSec = (double)count / (double)span.TotalSeconds;
        if (numPerSec == 0) numPerSec = 1;
        span = new TimeSpan(0, 0, (int)(num / numPerSec));
        string statusFile = string.Format("{0} of {1}", count, obj.Total);
        string statusTime = string.Format("{0}:{1}", span.Minutes.ToString("00"), span.Seconds.ToString("00"));
        _frmProgress.ProgressString = statusFile;
        _frmProgress.TimeLeftString = statusTime;
      }
    }
  } else {
    _frmProgress.HeaderText = "Working...";
  }
}
 
Finally: Background Complete
Code:
void Worker_FillDataGridComplete(object sender, RunWorkerCompletedEventArgs e) {
  _parent.AuthenticationReset();
  Cursor = Cursors.Default;
  _frmProgress.Close();
  if (e.Error == null) {
    if ((e.Result is ZTreeParam) && (e.Result != null)) {
      ZTreeParam tp = (ZTreeParam)e.Result;
      DataTable table = new DataTable(tp.DataSet1.DataSetName);
      foreach (DataTable dsTable in tp.DataSet1.Tables) {
        try {
          table.Merge(dsTable);
        } catch (Exception err) {
          Global.LogError("Reporter - Worker_FillDataGridComplete", err);
        }
      }
      DataGridView_Clear();
      DataGridView1.DataSource = table.DefaultView;
      if (DataGridView1.CurrentRow != null) {
        DataGridView1.CurrentRow.Selected = false;
      }
      UpdateStatusBar(string.Format("{0} records found", DataGridView1.Rows.Count));
      if (tp.ColumnName.IndexOf("System_ID") == -1) {
        if ((0 < DataGridView1.Rows.Count) &&
            (((tp.ColumnName == _EMPLOYEE) || (tp.ColumnName == "Operator"))
            || ((tp.ColumnName == _SERIALNUM) || (tp.ColumnName == "Coils"))
            || (_clearTree == true))) {
          List<string> StringList = new List<string>(DataGridView1.Rows.Count);
          for (int i = 0; i < DataGridView1.Rows.Count; i++) {
            DataGridViewRow row = DataGridView1.Rows[i];
            string value = string.Empty;
            if ((tp.ColumnName == _EMPLOYEE) || (tp.ColumnName == "Operator")) {
              value = row.Cells[tp.Column].Value.ToString().Trim();
              if (Action == MainAction.Reports) {
                if (-1 < value.IndexOf("Summary")) {
                  foreach (DataGridViewCell cell in row.Cells) {
                    cell.Style.BackColor = Color.Yellow;
                    cell.Style.SelectionBackColor = Color.Gold;
                  }
                }
                if (_ReportOpt[_nFilter1Key] == _LEAKSITES) { // nothing to do, I don't think.
                } else if (_ReportOpt[_nFilter1Key] == _INSPECTIONS) {
                  value = string.Empty;
                }
              }
            } else if ((tp.ColumnName == _SERIALNUM) || (tp.ColumnName == "Coils")) {
              value = row.Cells[tp.Column].Value.ToString().Trim();
              if ((Action == MainAction.Reports) && (_ReportOpt[_nFilter1Key] == _WORKORDER)) {
                if (0 < value.IndexOf("Total")) {
                  foreach (DataGridViewCell cell in row.Cells) {
                    cell.Style.BackColor = Color.Yellow;
                    cell.Style.SelectionBackColor = Color.Gold;
                  }
                } else {
                  if (AcpCoil.CheckFormat(value) == string.Empty) {
                    Color bgColor = (i % 2 == 0) ? Color.PaleGreen : Color.Lime;
                    for (int j = 4; (j < 11) && (j < row.Cells.Count); j++) {
                      string txt = row.Cells[j].Value.ToString();
                      if ((Global.IsNumeric(txt) == true) && (0 < Global.ToInt32(txt))) {
                        row.Cells[j].Style.BackColor = bgColor;
                        row.Cells[j].Style.SelectionBackColor = Color.Silver;
                      }
                    }
                  } else {
                    value = string.Empty;
                  }
                }
              }
            } else {
              Console.WriteLine(tp.ColumnName);
            }
            if (((value != string.Empty) && (StringList.Contains(value) == false)) ||
               //((Action == MainAction.Reports) && (m_ReportOpt[m_nFilter1Key] == m_LEAKSITES)) ||
               (value == "Leak Site Summary")
              ) {
              StringList.Add(value);
            }
          }
          if ((0 < StringList.Count) && (_clearTree == true)) {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_FillTreeComplete);
            if ((Action == MainAction.Reports) && (_ReportOpt[_nFilter1Key] == _LEAKSITES)) {
              List<DataRow> Rows = new List<DataRow>(StringList.Count);
              foreach (string emp in StringList) {
                bool ok = true;
                string[] split1 = emp.Split(new char[] { '(' });
                string[] split2 = split1[0].Substring(0, split1[0].Length).Trim().Split(_blankspace);
                string sql = string.Empty;
                if (split2.Length == 2) {
                  sql = string.Format("(FIRSTNAME Like '{0}%') AND (LASTNAME Like '%{1}')", split2[0], split2[1]);
                } else if (split2.Length == 3) {
                  sql = string.Format("((FIRSTNAME Like '{0}%') OR (FIRSTNAME Like '{1}%')) " +
                    "AND ((LASTNAME Like '%{1}') OR (LASTNAME Like '%{2}'))", split2[0], split2[1], split2[2]);
                } else {
                  ok = false;
                }
                if (ok == true) {
                  DataRow[] dr = Global.CpAppDataSet.Tables[_EMPLOYEEINFO].Select(sql);
                  DataRow tmp = null;
                  for (int i = 0; i < dr.Length; i++) {
                    if (tmp == null) {
                      tmp = dr[i];
                    } else {
                      if ((int)tmp["COUNT"] < (int)dr[i]["COUNT"]) {
                        tmp = dr[i];
                      }
                    }
                  }
                  if (tmp != null) Rows.Add(tmp);
                }
              }
              if (0 < Rows.Count) {
                worker.DoWork += new DoWorkEventHandler(Worker_FillTreeWithEmployees);
                worker.RunWorkerAsync(Rows.ToArray());
              }
            } else {
              worker.DoWork += new DoWorkEventHandler(Worker_FillTreeWithCoils);
              worker.RunWorkerAsync(StringList.ToArray());
            }
            if (worker.IsBusy == true) {
              Cursor = Cursors.WaitCursor;
            }
          } else {
            _clearTree = true; // subsequent searches will want to clear this tree information
          }
        } else {
          MessageBox.Show("No records found.", "Search Complete", MessageBoxButtons.OK, MessageBoxIcon.Information, 0);
        }
      }
      if (_cols2hide != null) {
        foreach (string col in _cols2hide) {
          if (DataGridView1.Columns.Contains(col) == true) {
            DataGridView1.Columns[col].Visible = false;
          }
        }
      }
      DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
      _footer = string.Format("{0} - {1} View\r\nCreated {2}", Title, tp.ColumnName, DateTime.Now);
    } else if (e.Result is string) {
      MessageBox.Show(e.Result.ToString());
      UpdateStatusBar(string.Format("Collect Data Error: {0}", e.Result.ToString()));
    }
  } else if (e.Error != null) {
    UpdateStatusBar(string.Format("Collect Data Error: {0}", e.Error.Message));
    _frmProgress.Close();
  } else if (e.Cancelled == true) {
    UpdateStatusBar("Data Collection was cancelled.");
    _frmProgress.Close();
  }
}
 
Back
Top