BackgroundWorker和Delegate方法没有写回主UI
本文关键字:写回 UI Delegate 方法 BackgroundWorker | 更新日期: 2023-09-27 18:22:17
要求将ListBox数据从业务逻辑类传递到主UI。
在我的主类(WindowsForm1)下,您将找到"backgroundWorkerDoWork"和Delegate方法:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Code.BusinessLogic bl = new Code.BusinessLogic();
bl.Process(backgroundWorker1);
}
public delegate void AddListBoxItemDelegate(object item);
public void AddListBoxItem(object item)
{
if (this.listBox1.InvokeRequired)
{
// This is a worker thread so delegate the task.
this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
}
else
{
// This is the UI thread so perform the task.
this.listBox1.Items.Add(item);
}
}
在业务逻辑类下,您将找到Process方法
public void Process(BackgroundWorker bg)
{
for (int i = 1; i <= 100; i++)
{
AddListBoxItem("Test");
Thread.Sleep(100);
bg.WorkerReportsProgress = true;
bg.ReportProgress(i);
}
}
在这种情况下,AddListBoxItem(来自Process Method)不会将项添加到主UI中
以下设置对我来说很好。
然而:正如之前的评论中所指出的,我不太确定设计师们想在这里归档什么。将后台工作者交给一个类,然后该类需要引用回工作者来源的表单,对我来说,这似乎过于复杂,与编码概念(即数据封装)不完全一致
考虑重写代码,让后台工作人员从业务逻辑中轮询完成其工作所需的数据,而不是将其交给业务逻辑并在其中工作。
在主窗口
public Form1()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Class1 bl = new Class1();
bl.f = this;
bl.Process(backgroundWorker1);
}
public delegate void AddListBoxItemDelegate(object item);
public void AddListBoxItem(object item)
{
if (this.listBox1.InvokeRequired)
{
// This is a worker thread so delegate the task.
this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
}
else
{
// This is the UI thread so perform the task.
this.listBox1.Items.Add(item);
}
}
在您的商业逻辑类中
class Class1
{
public Form1 f { get; set; }
public void Process(BackgroundWorker bg)
{
for (int i = 1; i <= 100; i++)
{
f.AddListBoxItem("Test");
Thread.Sleep(100);
bg.WorkerReportsProgress = true;
bg.ReportProgress(i);
}
}
}