-2

这是 DoWork:

private void uploadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            uploadWorker.ReportProgress(20);

            int tiffError = 0;

            finalFiles = Directory.GetFiles(AppVars.FinalPolicyImagesFolder);

            foreach (string file in finalFiles)
            {
                if (!file.EndsWith(".tiff"))
                {
                    tiffError = 1;
                    break;
                }
            }

            uploadWorker.ReportProgress(50);

            if (tiffError == 1)
            {
                MessageBox.Show("There are files in this folder that are not .tiff. Please ensure only .tiff files are in this folder.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (finalFiles.Length == 0)
                {
                    MessageBox.Show("There are no TIFF files to be uploaded. Please generate files first.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    pbUpload.Value = 0;
                    EnableAllButtons();
                }
                else
                {
                    double count = finalFiles.Length;
                    int current = 0;
                    int pbValue = 0;

                    uploadWorker.ReportProgress(70);

                    foreach (string file in finalFiles)
                    {
                        current = current + 2;

                        if (file.Contains(".tiff") == true)
                        {
                            PolicyNumber = Path.GetFileName(file).Split('_')[0];
                            basePolicyNumber = PolicyNumber.Remove(PolicyNumber.Length - 2);
                            basePolicyNumber = basePolicyNumber + "00";

                            finalPolicyName = Path.GetFileName(file);

                            PolicyUUID = Transporter.GetPolicyUUID(AppVars.pxCentralRootURL, basePolicyNumber);

                            if (PolicyUUID == "")
                            {
                                MessageBox.Show("The InsightPolicyID for the policy you are trying to upload does not exist in ixLibrary. Please ensure the policy number is correct. If you are sure it should be in ixLibray, please contact IT.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                ixLibrarySourceFileURL = AppVars.ixLibraryPolicyAttachmentsURL + finalPolicyName;

                                UploadToixLibraryErrorCode = Transporter.UploadFileToixLibrary(AppVars.ixLibraryPolicyAttachmentsURL, file);

                                if (UploadToixLibraryErrorCode != 0)
                                {
                                    MessageBox.Show("There was an error uploading the file to ixLibrary. Please contact IT about this problem.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                else
                                {
                                    GeneratePayLoadErrorCode = Transformer.GeneratePayLoad(ixLibrarySourceFileURL, finalPolicyName);

                                    if (GeneratePayLoadErrorCode != 0)
                                    {
                                        MessageBox.Show("There was an error generating the XML for pxCentral. Please contact IT about this problem.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        pxCentralPOSTErrorCode = Transporter.pxCentralPOST(AppVars.pxCentralRootURL + PolicyUUID, AppVars.pxCentralXMLPayloadFilePath);

                                        pbValue = Convert.ToInt32(((current / count) * 30) + 70);

                                        uploadWorker.ReportProgress(pbValue);
                                    }
                                }
                            }
                        } 
                    }
                }
            }
        }

一旦它到达最后一个},我就会在此处收到 TargetInvocationException 未处理错误(请参阅代码中的注释):

static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool createdNew = false;

            Mutex mutex = new Mutex(true, "MyApplicationMutex", out createdNew);

            if (createdNew == true)
            {
                //error happens here
                Application.Run(new frmMain());
            }
            else
            {
                MessageBox.Show("The application is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }

我不确定为什么会突然发生这种情况。有谁知道为什么?

最后,这是 RunWorkerCompleted:

private void uploadWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DeleteFinalFiles(finalFiles);
                MessageBox.Show("Upload process complete.", "Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            EnableAllButtons();
        }
4

4 回答 4

3

您正在调用EnableAllButtons您的DoWork处理程序。这大概会改变Enabled表单上按钮的状态。这对于 UI 线程以外的任何其他线程都是不合法的。您应该EnableAllButtonsProgressChanged事件处理程序或RunWorkerCompleted事件处理程序中进行调用。您还使用代码调用ProgressBar.ValueDoWorkpbUpload.Value = 0

此外,您应该MessageBox.Show从您的 UI 线程(即 inProgressChangedRunworkerCompleted处理程序)调用,以便MessageBox可以与您的表单消息泵正确关联。您应该传递一个表单对象以MessageBox.Show将消息框与表单相关联,这样您就不能在显示消息框时将表单带到前台。例如:

MessageBox.Show(this, 
    "There are files in this folder that are not .tiff. Please ensure only .tiff files are in this folder.", 
    "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
于 2012-08-28T15:39:24.177 回答
0

我在后台进程完成后引发的 TargetInvocation Exception 遇到了完全相同的问题。在 backgroundWorker ProgressChanges 事件中,我引用了如下所示的控件`private void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {

       // This function fires on the UI thread so it's safe to edit
       // the UI control directly, no funny business with Control.Invoke :)
       CurrentState state =
               (CurrentState)e.UserState;
       txtProgress.Text = state.CrawlStatus;
       lblStatus2.Text = state.sStatus;
       txtItemsStored.Text = state.TotItems.ToString() + " items";
       txtLastRunTime.Text = state.MostRecentGatherDate.ToString();
       AppNameKey.SetValue("LastCrawlTime", txtLastRunTime.Text);
   }`

DoWork 事件从控件中读取

private  void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
   {

       DateTime LastCrawlTime;
       try
       {
         LastCrawlTime = Convert.ToDateTime(txtLastRunTime.Text);
        if (lblStatus2.Text != "Status: Running" || (!cmdRunNow.Enabled && cmdStopRun.Enabled)) // run is not currently running or cmdRunNow clicked
        {
            //lblStatus2.Text = "Status: Running";
            GetUpdated(LastCrawlTime,e);
        }
       }
       catch (Exception Ex)
       {
           MessageBox.Show(Ex.Message);
       }

   }

RunWorkedrCompleted 事件写入控件:

void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
   {
        if (e.Cancelled)
       {
           lblStatus2.Text = "Status: Stopped";
           cmdStopRun.Enabled = false;
       }
       // Check to see if an error occurred in the background process.
       else if (e.Error != null)
       {
           lblStatus2.Text = "Fatal Error while processing.";
       }
       else
       {
           // Everything completed normally.
           //CurrentState state = (CurrentState)e.UserState;
           lblStatus2.Text = "Status: Finished";            
       }

   }

这些都没有引起问题。导致问题的原因是尝试在 RunWorker_Completed 事件中引用 e.UserState(上面已注释掉)

于 2014-09-21T03:44:16.737 回答
0

在 WinForms 中,您只能访问创建控件的线程上的控件。您的 DoWork 事件处理程序未在创建表单的线程上运行(这当然是重点)。因此,您不得在 DoWork 处理程序中访问表单上的任何控件。这样做会产生不可预知的结果。

于 2012-08-28T15:28:55.810 回答
-1

我弄清楚了这个问题。

进度条超出了允许的最大值(100)。

问题是在代码中,我是这样递增进度条的:

current = current + 2;

我将其替换为:

current++;

我增加 2 的原因仅仅是为了测试目的。

于 2012-08-28T15:35:14.920 回答