简体   繁体   中英

After my background worker is complete, I want to change labels on my form. Where should I add this code?

After the background worker is done doing its process, I want to change the text on certain labels on the form.

Here's the Button that fires the backgroundworker:

private void btnProcessImages_Click(object sender, EventArgs e)
        {
            DialogResult processImagesWarnMsg = MessageBox.Show("You're about to process images, are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

            if (processImagesWarnMsg == DialogResult.Yes)
            {
                DisableAllButtons();

                if (!processImagesWorker.IsBusy)
                {
                    processImagesWorker.RunWorkerAsync();
                }
                //The problem here is that the below will run BEFORE the worker is complete. Where should I place the below method in my code? 
                //ResetDirectoryStatistics();
            }
        }

Here's the method that changes text for the labels on the form:

private void ResetDirectoryStatistics()
        {
            lblSelectedDirectory.Text = "N/A";
            lblTotalNumberOfFilesInDirectory.Text = "N/A";
            lblTotalNumberOfSupportedFilesInDirectory.Text = "N/A";
            lblTotalNumberOfUnsupportedFilesInDirectory.Text = "N/A";
            lblTotalNumberOfPoliciesInDirectory.Text = "N/A";
        }

When dealing with the background worker, where should I place the ResetDirectoryStatistics method? I cannot place it in the "DoWork" method of the backgroundworker because that would be cross-threading. And if I place the method right after processImagesWorker.RunWorkerAsync();, it'll execute itself before RunWorker is complete.

You should call your method in the RunWorkerCompleted event of the background worker. This event uses the UI thread, so no cross-threading issue to fear.

You just need to put all of your code in the RunWorkerCompleted event of the BackgroundWorker .

It will even take care of ensuring that the event runs in the UI thread, so you don't need to worry about invoking or anything like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM