这可能看起来像一个有点人为的例子,但我只是在挠头.
好的,我有一个控制台应用程序,它实例化一个WindowsForm并在窗体上调用一个名为DoSomeWork()的方法.
class Program { static void Main(string[] args) { Form1 form = new Form1(); form.DoSomeWork(); } }
Form1看起来像这样......
public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void DoSomeWork() { OuterClass outerClass = new OuterClass(); outerClass.DoSomeWork(); } }
反过来,外类看起来像......
public class OuterClass { public void DoSomeWork() { InnerClass innerClass = new InnerClass(); innerClass.DoSomeWork(); } }
最后,InnerClass看起来像这样......
public class InnerClass { private BackgroundWorker _backgroundWorker = new BackgroundWorker(); public InnerClass() { _backgroundWorker.WorkerReportsProgress = true; _backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork); _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged); } void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { int i = 0; //I've placed a break point here. But it's never hit } void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; worker.ReportProgress(42); } public void DoSomeWork() { _backgroundWorker.RunWorkerAsync(); } }
由于一个未知的原因(对我而言),InnerClass中的BacgroundWorker似乎永远不会触发ProgressChanged事件.如果我更换
Form1 form = new Form1();
同
OuterClass outerClass = new OuterClass()
在课程计划中,它工作正常.那么,当我通过表单调用相同的方法时,为什么我的事件不会触发?
谢谢!
编辑:我似乎是通过将ProgressChanged事件处理程序保留为抛出NotImplementedException来抛弃人员,所以我为了清楚起见删除了它.
您忘记启动消息循环,需要调用Application.Run().如果没有消息循环,BackgroundWorker事件将无法工作.修理:
static void Main(string[] args) { Application.Run(new Form1()); }
在窗体的构造函数中调用DoSomeWork()或它的Load事件.