-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スレッド以外のスレッドからは合法ではありません。イベントハンドラーまたはイベントハンドラーでを呼び出す必要がありEnableAllButtonsます。また、コードを使用してを呼び出しています。ProgressChangedRunWorkerCompletedProgressBar.ValueDoWorkpbUpload.Value = 0

また、MessageBox.ShowUIスレッド(つまり、inProgressChangedまたはRunworkerCompletedhandler)から呼び出し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

WinFormsでは、コントロールを作成したスレッドのコントロールにのみアクセスする必要があります。DoWorkイベントハンドラーは、フォームを作成したスレッドで実行されていません(もちろん、これがポイントです)。したがって、DoWorkハンドラーのフォームのコントロールにアクセスしないでください。これを行うと、予測できない結果が生じる可能性があります。

于 2012-08-28T15:28:55.810 に答える
0

バックグラウンドプロセスの完了後に発生したTargetInvocationExceptionでまったく同じ問題が発生しました。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 に答える
-1

私はその問題を理解しました。

プログレスバーが最大許容値(100)を超えていました。

問題は、コードでプログレスバーを次のようにインクリメントしていたことです。

current = current + 2;

私はそれを次のように置き換えました:

current++;

私が2ずつ増やしていた理由は、単にテスト目的のためでした。

于 2012-08-28T15:35:14.920 に答える