如果发生错误,如何在RunWorkerCompleted事件中绕过代码?

时间:2018-11-02 22:33:16

标签: c# backgroundworker

我编写了一个程序,该程序可以从Excel电子表格的内容创建XML文件。该程序有效,我现在通过添加错误检查使其更强大。例如,如果Excel电子表格不包含必需的XML标记,则程序将显示错误并从主程序返回。发生错误时,将触发RunWorkerCompleted()事件,并执行不应执行的代码,因为发生了错误。我的问题是如何确定是否发生错误,以便可以绕过RunWorkerCompleted()事件中的某些代码。

我尝试在检测到错误的主程序中调用bgw.CancelAsync(),但是RunWorkerCompletedEventArgs e.Cancelled为false,所以它不起作用。

这是我的代码的一些摘录。进度条在按钮的单击事件中启动。它可以工作,但是我不得不将cellProcessed,rowCount和colCount声明为全局,因为我不知道如何将它们传递给bgw_DoWork()。

private void button_create_Click(object sender, EventArgs e)
{
   // Define the event that fires when the progress bar finishes
   bgw.RunWorkerCompleted += bgw_Complete;

        rowCount = xmlRange.Rows.Count; // Declared as global
        colCount = xmlRange.Columns.Count;  // Declared as global

        // Start the progress bar thread
        if (!bgw.IsBusy)
        {
            bgw.RunWorkerAsync();
        }

        // Read the header in row 1 and return an error if it isn't valid
        for (colIdx = 1; colIdx <= colCount; colIdx++)
        {
            if ((xmlRange.Cells[1, colIdx] != null) && (xmlRange.Cells[1, colIdx].Value2 != null))
            {
                cellContents = xmlRange.Cells[1, colIdx].Value2.ToString();

                switch (colIdx)
                {
                    case 1:
                        if (cellContents != "Tag")
                        {
                            error = true;
                            errText = "Cell A1 must contain 'Tag'";
                        }
                        break;
                    case 2:
                        if (cellContents != "Type")
                        {
                            error = true;
                            errText = "Cell B1 must contain 'Type'";
                        }
                        break;
   if (error)
   {

      bgw.CancelAsync();
      MessageBox.Show(errText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

      // Close Excel resources
      xmlWorkbook.Close();
      xmlSpreadsheet.Quit();
      Marshal.ReleaseComObject(xmlRange);
      Marshal.ReleaseComObject(xmlWorksheet);
      Marshal.ReleaseComObject(xmlWorkbook);
      Marshal.ReleaseComObject(xmlSpreadsheet);
      GC.Collect();

      return;
   }

    private void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        if (bgw.CancellationPending)
        {
            e.Cancel = true;
        }
        else
        {
            label_pctComplete.Text = "Completed " + progressBar.Value.ToString() + "%";
            bgw.ReportProgress((100 * ++cellsProcessed) / (rowCount * colCount));
        }
    }

    private void bgw_Complete(object sender, RunWorkerCompletedEventArgs e)
    {
        if (!e.Cancelled)
        {
            label_pctComplete.Visible = false;
            progressBar.Visible = false;

            // Inform the user that the XML file was created
            label_created.Visible = true;
            label_created.Text = "Done!...Created " + textBox_outputFile.Text;

            // Enable the button so the user can view the XML Limit File
            button_openLimitFile.Enabled = true;
        }
    }

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

谢谢您的帮助。

0 个答案:

没有答案