我正在尝试编写我的应用程序的一部分,该应用程序运行一个BackgroundWorker
执行耗时操作的进程。在主线程中,计时器更新进度条(这是此问题的延续)。但是,此代码显示 no MessageBoxes
。foreach (String word in this.words)
在事件处理程序的行上设置断点SearchButton_Click
表明this.words
没有值,即this.words.Count() == 0
.
public partial class Form1 : Form
{
System.Windows.Forms.Timer searchProgressTimer;
List<String> words;
public Form1()
{
InitializeComponent();
words = new List<String>(3);
}
private void SearchDatabase_Click(object sender, EventArgs e)
{
this.searchProgressTimer.Start();
SearchBackgroundWorker.RunWorkerAsync();
foreach (String word in this.words) // BREAKPOINT HERE
MessageBox.Show(word);
}
private void SearchBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Time-consuming operation
String filename = @"http://www.bankofengland.co.uk/publications/Documents/quarterlybulletin/qb0704.pdf";
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(filename), @"file.pdf");
List<String> word_result = new List<String> { "word1", "word2", "word3" };
e.Result = word_result; // e.result is an Object, and word_result is a List.
}
private void SearchBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.searchProgressTimer.Stop();
this.searchProgressBar.Value = 0;
this.words = (List<String>)e.Result;
}
}
我对为什么会发生这种情况的猜测是因为在主 UI 线程移动到循环BackgroundWorker
之前线程尚未完成其操作。foreach
我想我理解那部分。但是,由于我想在后台线程中执行耗时的操作,因此进度条可以在所述操作运行时更新其值,然后BackgroundWorker
在完成后立即使用结果,我该怎么做?
如果我的标题也没有得到理解,请编辑我的标题。我不知道该怎么表达。