我正在尝试使用 BackgroundWorker,并尝试根据事件通知我的主线程。这些东西对我来说都是新的,想问一下,如果我做得很好。
我通过以下方式简化了我的一个winforms问题:(它只有一个按钮,当我按下它时在另一个线程中计数到十)
public partial class Form1 : Form
{
public void Subscribe(CountToTen c)
{
c.HandleWorkerEvent += new CountToTen.WorkerHandler(OtherThreadFinished);
}
private void OtherThreadFinished(CountToTen c, EventArgs e)
{
Debug.WriteLine("I'm ready !!!");
}
public Form1()
{
InitializeComponent();
}
private void btn_do_Click(object sender, EventArgs e)
{
CountToTen newThread = new CountToTen();
Subscribe(newThread);
newThread.StartCountingAndReportIfFinished();
}
}
CountToTen 类:
public class CountToTen
{
public event WorkerHandler HandleWorkerEvent;
public EventArgs e;
public delegate void WorkerHandler(CountToTen c, EventArgs e);
public void StartCountingAndReportIfFinished()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(300);
Debug.WriteLine("Counting :" + i.ToString());
}
};
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs args)
{
Debug.WriteLine("Fromt Thread2 : I am finished!");
if (HandleWorkerEvent != null)
{
HandleWorkerEvent(this, e);
}
});
worker.RunWorkerAsync();
worker.Dispose();
}
}
我试图在 BW 完成后创建一个事件,并在我的主窗体中订阅此事件。它工作正常,但是,我真的不明白这一行发生了什么:
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs args)
{
Debug.WriteLine("Fromt Thread2 : I am finished!");
if (HandleWorkerEvent != null)
{
HandleWorkerEvent(this, e);
}
});
我不是在这里为我的 BW 创建一个事件,当它完成后,然后为主线程调用另一个?这不是矫枉过正吗?我也可以直接订阅 RunWorkerCompleteEventHandler 吗?
我这里有点困惑,请初学者赐教。谢谢