gpt4 book ai didi

c# - 如何从 BackgroundWorker 返回列表以供 UI 线程中的下一行代码使用?

转载 作者:行者123 更新时间:2023-12-03 21:47:13 25 4
gpt4 key购买 nike

我正在尝试对运行 BackgroundWorker 进程的应用程序的一部分进行编码,该进程执行一项耗时的操作。在主线程中,计时器更新进度条(这是 this question 的延续)。但是,此代码不显示 MessageBoxes。在 SearchButton_Click 事件处理程序的 foreach (String word in this.words) 行上设置断点显示 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 线程移动到 foreach 循环之前,BackgroundWorker 线程尚未完成其操作。我想我理解那部分。但是,由于我想在后台线程中执行耗时的操作,因此进度条可以在所述操作运行时更新其值,然后在完成后立即使用 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);
}

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

关于c# - 如何从 BackgroundWorker 返回列表以供 UI 线程中的下一行代码使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11477558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com