让我们假设我们有两种形式:MainForm
和WaitingForm
。我想从MainForm
传递给WaitingForm
方法,以使用BackgroundWorker
在后台运行。
现在,我正在这样做:
MainForm.cs
:
public partial class MainForm: Form
{
private void btnImport_Click(object sender, EventArgs e)
{
var waitingFrm = new WaitingForm();
waitingFrm.DoWork = (o, args) => this.LongRunningOperation(this, new DoWorkEventArgs("foo bar"));
waitingFrm.OnWorkCompleted = (o, args) => MessageBox.Show("Finished!");
waitingFrm.Show();
waitingFrm.Run(); // should execute LongRunningOperation, method below.
}
private void LongRunningOperation(object sender, DoWorkEventArgs e)
{
MessageBox.Show("Running long operation!....");
// some long running stuff here;
}
}
WaitingForm.cs
public partial class WaitingForm: Form
{
private BackgroundWorker worker = new BackgroundWorker();
public DoWorkEventHandler DoWork { get; set; }
public RunWorkerCompletedEventHandler OnWorkCompleted { get; set; }
public WaitingForm()
{
this.worker.DoWork += DoWork;
this.worker.RunWorkerCompleted += OnWorkCompleted;
InitializeComponent();
}
public void Run()
{
this.worker.RunWorkerAsync();
}
}
但在waitingFrm.Run();
之后我的LongRunningOperation
未执行。
答案 0 :(得分:1)
在你的WaitingForm中,我会这样做:
public event DoWorkEventHandler DoWork {
add { worker.DoWork += value; }
remove { worker.DoWork += value; }
}
(而不是get; set;属性)。
然后在主窗口btnImport_Click
处理程序中:
waitingFrm.DoWork += LongRunnignOperation;
对于已完成的处理程序也一样。你的语法似乎过于复杂。这只是一种公开事件(在这种情况下在您的waitingform上)和传递事件处理程序到真实处理程序(在本例中为worker.DoWork)的简洁方法。它相当于
waitingFrm.worker.DoWork += LongRunnignOperation;
也可以。
答案 1 :(得分:1)
我想从MainForm传递给WaitingForm运行的方法 在后台使用BackgroundWorker
我会在这种情况下
WaitingForm
Form1
显示WaitingForm
订阅该事件之前WaitingForm
举起一个事件,Form1
得到它并且
Form1
在其他线程中运行其方法。 希望这会有所帮助。
答案 2 :(得分:1)
在这种特殊情况下,您希望在MainForm
中完成所有工作,看起来WaitingForm
只是用户的显示。如果是这种情况,那么我只需将BackgroundWorker
放入MainForm
并使用该事件调用WaitingForm
public partial class MainForm: Form
{
private void btnImport_Click(object sender, EventArgs e) {
var waitingForm = new WaitingForm();
waitingForm.Show();
var worker = new BackgroundWorker();
worker.DoWork += (o, args) => this.LogRunningOperation(o, args);
worker.OnWorkComplete += (o, args) => {
waitingForm.Close();
worker.Dispose();
};
worker.RunWorkerAsync();
}
private void LongRunningOperation(object sender, DoWorkEventArgs e) {
MessageBox.Show("Running long operation!....");
// some long running stuff here;
}
}
答案 3 :(得分:1)
所以,简单的答案是。您的代码无法正常工作,因为主窗体看不到 BackgroundWorker对象实例事件。而不是做:
this.worker.DoWork += DoWork;
this.worker.RunWorkerCompleted += OnWorkCompleted;
在WaitingForm - InitializeComponent()中,在mainForm中执行此操作,如下所示:
waitingFrm.worker.DoWork += waitingFrm.DoWork;
waitingFrm.worker.RunWorkerCompleted += waitingFrm.OnWorkCompleted;