Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在DoWork Backgroundworker方法的末尾未处理TargetInvocationException_C#_Backgroundworker_Targetinvocationexception - Fatal编程技术网

C# 在DoWork Backgroundworker方法的末尾未处理TargetInvocationException

C# 在DoWork Backgroundworker方法的末尾未处理TargetInvocationException,c#,backgroundworker,targetinvocationexception,C#,Backgroundworker,Targetinvocationexception,这是道具: private void uploadWorker_DoWork(object sender, DoWorkEventArgs e) { uploadWorker.ReportProgress(20); int tiffError = 0; finalFiles = Directory.GetFiles(AppVars.FinalPolicyImagesFolder);

这是道具:

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 was unhandled错误(请参见代码中的注释):

我不知道为什么会突然发生这种事。有人知道为什么吗

最后,这里是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();
        }

在WinForms中,只能访问创建控件的线程上的控件。DoWork事件处理程序没有在创建表单的线程上运行(当然,这是关键)。因此,您不能在DoWork处理程序中访问窗体上的任何控件。这样做会产生不可预测的结果。

我发现了这个问题

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

问题在于,在代码中,我增加了进度条:

current = current + 2;
我将其替换为:

current++;

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

您正在调用
DoWork
处理程序中的
EnableAllButtons
。这可能会更改窗体上按钮的
启用状态。这对于UI线程以外的任何其他线程都是不合法的。您应该在
ProgressChanged
事件处理程序或
RunWorkerCompleted
事件处理程序中调用
EnableAllButtons
。您还在
DoWork
中调用
ProgressBar.Value
,代码
pbUpload.Value=0

此外,您应该从UI线程(即在
ProgressChanged
RunworkerCompleted
处理程序中)调用
MessageBox.Show
,以便
MessageBox
可以与表单消息泵正确关联。您应该将表单对象传递给
MessageBox.Show
以将消息框与表单关联,这样在显示消息框时就不能将表单置于前台。e、 g:

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);

在完成后台处理后,我遇到了与TargetInvocation Exception完全相同的问题。在backgroundWorker ProgressChanges事件中,我引用了如下所示的控件` private void m_owworker_ProgressChanged(对象发送方,ProgressChangedEventArgs e) {

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);
       }

   }
RunWorkedCompleted事件写入控件:

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(上面已注释)

您的后台工作人员的
RunWorkerCompleted
事件处理程序中可能有问题。我在OP中添加了它,检查它只是一个简单的镜头,但您可能需要确保您没有涉及某种跨线程执行问题,例如,在单独线程上调用表单、后台线程运行、UI控件受影响非UI线程。应显示一个显式错误,但在本例中可能是另一种表现形式…@AmiramKorach,我检查了它并找出了问题所在。在doWork中,我超过了最大进度条值(100),显示为130…我修复了此问题并解决了问题。谢谢!!@Testifier如果这是您的问题,请将其作为答案发布并接受,以便将来的访问者能够更清楚地看到答案。在
DoWork
中访问的控件是什么?
pbUpload
似乎是一个控件,并且调用
EnableAllButtons()
将按名称操作表单上的按钮。这不会导致
targetingException
它将导致
系统。ArgumentOutOfRangeException
如果您在错误线程上设置了
targetingException
进度条
设置为超出范围的值时,您将得到一个
ArgumentOutOfRangeException
。更改进度条
设置为的值并不能消除
目标职业异常
。如果这不是您遇到的问题,请不要将其放在标题中。@PeterRitchie,这正是我看到的错误接收时。然后,当我看到其他人在这里提到的内部异常时,我看到了错误所在,这就是progressbar值问题。修复进度条值修复了我的问题,TargetInvocationException消失了。不要相信我,自己做,自己看。你仍然有
pbUpload.value=0;
EnableAllButtons();
在您的DoWork方法中,这将导致您出现问题
pbUpload
是一个
ProgressBar
EnableAllButtons
按钮
对象执行任何操作。
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);
       }

   }
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";            
       }

   }