[英]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? 与后台工作人员打交道时,应在哪里放置ResetDirectoryStatistics方法? I cannot place it in the "DoWork" method of the backgroundworker because that would be cross-threading. 我无法将其放置在backgroundworker的“ DoWork”方法中,因为那样会产生交叉线程。 And if I place the method right after processImagesWorker.RunWorkerAsync();, it'll execute itself before RunWorker is complete. 并且,如果将方法放在processImagesWorker.RunWorkerAsync();之后,它将在RunWorker完成之前自行执行。
You should call your method in the RunWorkerCompleted
event of the background worker. 您应该在后台工作程序的RunWorkerCompleted
事件中调用您的方法。 This event uses the UI thread, so no cross-threading issue to fear. 此事件使用UI线程,因此不必担心跨线程问题。
You just need to put all of your code in the RunWorkerCompleted
event of the BackgroundWorker
. 您只需要将所有代码放在BackgroundWorker
的RunWorkerCompleted
事件中即可。
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. 它甚至会确保事件在UI线程中运行,因此您无需担心调用之类的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.