为BackgroundWorker设计接口

时间:2009-05-11 13:46:54

标签: c# .net backgroundworker

在我的Windows窗体应用程序中,我有一个扩展backgroundworker的类,让我们在我的表单类中将其称为ExtendedBGW1.cs我将其声明为成员变量,因此我有整个类的范围,如下所示:

public partial class Main : Form
{
    ExtendedBGW1 ebgw1;
}

稍后在表单构造函数中我这样做

public Main()
{
    InitializeComponent();

    ebgw1 = new ExtendedBGW1();

    InitializeBackgoundWorker();
}

我的InitializeBackgroundWoker()方法看起来像这样

private void InitializeBackgoundWorker()
{
    ebgw1.DoWork += new DoWorkEventHandler(ebgw1.worker_DoWork);
    ebgw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(processWorkerCompleted);
    ebgw1.ProgressChanged += new ProgressChangedEventHandler(processProgressChanged);
    ebgw1.WorkerReportsProgress = true;
    ebgw1.WorkerSupportsCancellation = true;
}

现在出现了我的设计问题。我现在知道我将有更多类,比如我的extenededBGW1.cs,它将扩展BackGroundWorker,所以我想如果我创建一个IExtenedBackGroundWorker,我可以做这样的事情。

public partial class Main : Form
{
    IExtenedBackGroundWorker ebgw1;
}

并且仍然具有Main类的适当范围。然后我可以创建我以后需要的IExtendedBackGroundWorker的任何实现。

我可以在没有太多问题的情况下为方法和属性创建接口,但是当我尝试在基类和Main类的接口之间正确连接事件时,我确实遇到了问题。

有没有人有任何想法?

以下是我在Main

中遇到的错误
Error   1   Cannot assign to 'DoWork' because it is a 'method group'

这是我在界面实现中遇到的错误

Error   5   The event 'System.ComponentModel.BackgroundWorker.DoWork' can only appear on the left hand side of += or -= 

这是我的界面现在的样子:

interface IExtendedBackGroundWorker 
{
    bool IsBusy { get; }

    bool WorkerReportsProgress { get; set; }

    bool WorkerSupportsCancellation { get; set; }

    List<CompareObject> ObjList { get; set; }

    string FilePath { get; set; }

    void RunWorkerAsync();

    void CancelAsync();

    void DoWork();

    void worker_DoWork(object sender, DoWorkEventArgs e);

    void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e);

    void ProgressChanged(object sender, ProgressChangedEventArgs e);
}

1 个答案:

答案 0 :(得分:9)

简单,只需1 - 2 - 3 - 完成

public interface IMyWorker
{
    bool WorkerReportsProgress { get; set; }
    bool WorkerSupportsCancellation { get; set; }
    event DoWorkEventHandler DoWork;
    event ProgressChangedEventHandler ProgressChanged;
    event RunWorkerCompletedEventHandler RunWorkerCompleted;
}

public class MyWorker : BackgroundWorker, IMyWorker
{

}

用法:

namespace stackOverflow
{
class Program
{
    static void Main(string[] args)
    {
        IMyWorker worker = new MyWorker();
        worker.DoWork += new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
    }

    static void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        throw new NotImplementedException();
    }
  }
}

玩得开心:)