这似乎是一个有点做作的例子,但我只能摸不着头脑。
好的,我有一个控制台应用程序,它实例化一个 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 来让人们失望,所以为了清楚起见,我已经删除了它。