Ric*_*ano 2 c# backgroundworker winforms
我正在尝试编写运行BackgroundWorker执行耗时操作的进程的应用程序的一部分.在主线程中,计时器更新进度条(这是此问题的延续).但是,此代码显示没有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;
}
}
Run Code Online (Sandbox Code Playgroud)
我猜测为什么会发生这种情况是因为BackgroundWorker在主UI线程移动到foreach循环之前线程没有完成其操作.我想我理解那一部分.但是,由于我想在后台线程中执行耗时的操作,因此进度条可以在所述操作运行时更新其值,然后BackgroundWorker在完成后立即使用结果,我该怎么做?
如果它没有得到重点,请编辑我的标题.我不知道怎么说这个.
在RunWorkerCompleted事件中执行任何您想要执行的操作:
private void SearchBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.searchProgressTimer.Stop();
this.searchProgressBar.Value = 0;
this.words = (List<String>)e.Result;
foreach (String word in this.words) // BREAKPOINT HERE
MessageBox.Show(word);
}
Run Code Online (Sandbox Code Playgroud)
由于您是从后台工作人员那里获取此信息,因此您知道自己的列表的唯一方法是工作人员完成时.
| 归档时间: |
|
| 查看次数: |
3098 次 |
| 最近记录: |