有几种方法:
禁止订阅并禁止触发
可以将子类写入 (a) 如果调用者尝试直接订阅ProcessChange
事件,则抛出异常,并且 (b) 根本不引发事件。请注意,单独的 (a) 并不能阻止事件被订阅,因为调用者可以将子类转换为 aBackgroundWorker
并直接订阅事件:
class ExtendedBackgroundWorker : BackgroundWorker
{
public new event ProgressChangedEventHandler ProgressChanges
{
add { throw new InvalidOperationException("This event cannot be added directly"); }
remove {}
}
protected override void OnProgressChanged(ProgressChangedEventArgs e)
{
// do not call base.OnProgressChanged
}
}
使用组合代替继承
但是,如果可能的话,更好的方法可能是根本不继承BackgroundWorker
。ABackgroundWorker
使用ProgressChanged
事件报告进度变化;如果它不这样做,它就不是一个BackgroundWorker
. 相反,考虑将 BackgroundWorker 实现为私有类成员,并根据需要从成员中公开成员,例如:
class CustomBackgroundWorker : Component
{
private BackgroundWorker worker;
public event ProgressChangedEventHandler FirstEvent;
public event ProgressChangedEventHandler SecondEvent;
public event DoWorkEventHandler DoWork
{
add { worker.DoWork += value; }
remove { worker.DoWork -= value; }
}
public event RunWorkerCompletedEventHandler RunWorkerCompleted
{
add { worker.RunWorkerCompleted += value; }
remove { worker.RunWorkerCompleted -= value; }
}
public CustomBackgroundWorker()
{
worker = new BackgroundWorker();
worker.ProgressChanged += OnProgressChanged;
worker.WorkerReportsProgress = true;
}
public void RunWorkerAsync()
{
worker.RunWorkerAsync();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
worker.Dispose();
}
private void OnProgressChanged(object o, ProgressChangedEventArgs e)
{
// code to handle progress change reports from the worker
}
}
重新触发事件以供客户使用
子类可以将它与其他事件结合使用(而不是作为替代),而不是抑制对事件的使用,以向订阅者提供相关信息(例如,总操作的进度)。