2

我正在尝试编写我的应用程序的一部分,该应用程序运行一个BackgroundWorker执行耗时操作的进程。在主线程中,计时器更新进度条(这是此问题的延续)。但是,此代码显示 no MessageBoxesforeach (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在完成后立即使用结果,我该怎么做?

如果我的标题也没有得到理解,请编辑我的标题。我不知道该怎么表达。

4

1 回答 1

7

在 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);
}

由于您是从后台工作人员那里获取此信息,因此您知道您拥有列表的唯一方法是工作人员完成时。

于 2012-07-13T20:08:53.827 回答