如何通知窗体在其他类中执行线程
本文关键字:其他 执行 线程 窗体 何通知 通知 | 更新日期: 2023-09-27 18:01:44
我有两个表单叫做frm1和frm2:
public partial class frm1 : Form
{
private WebMethods wm;
public frm1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
wm = new WebMethods();
wm.test();
}
}
public partial class frm2 : Form
{
private WebMethods wm;
public frm2()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
wm = new WebMethods();
wm.test();
}
}
现在我有一个类叫做WebMethods:
class WebMethods
{
private BackgroundWorker backgroundWorker;
public void stop(){
backgroundWorker.CancelAsync();
}
public void test()
{
if (backgroundWorker.IsBusy != true)
{
this.backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += new DoWorkEventHandler(_PostRequest);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_PostRequestComplet ed);
backgroundWorker.RunWorkerAsync();
}
}
private void _PostRequest(object sender, DoWorkEventArgs e)
{
// ...
}
private void _PostRequestCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// ...
}
}
现在我想当backgroundworker线程完成并且_PostRequestCompleted事件执行时,它通知窗体执行了test()方法。
例如,如果frm1执行test()方法在end _PostRequestCompleted()方法通知frm1线程已经完成。例如_PostRequestCompleted在完成线程后执行frm1中的方法。但是我不知道怎么做??
在WebMethods
类中声明event
并将其注册到您的表单类中
class WebMethods
{
public event EventHandler PostRequestCompletedEvent;
private void _PostRequestCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// ...
if (PostRequestCompletedEvent != null)
{
PostRequestCompletedEvent(this, new EventArgs());
}
}
}
现在在您的表单类中注册此事件。
public partial class frm1 : Form
{
private WebMethods wm;
public frm1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
wm = new WebMethods();
wm.PostRequestCompletedEvent += wm_PostRequestCompletedEvent;
wm.test();
}
void wm_PostRequestCompletedEvent(object sender, EventArgs e)
{
// notify frm1 that thread was finished
}
}
public partial class frm2 : Form
{
private WebMethods wm;
public frm2()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
wm = new WebMethods();
wm.PostRequestCompletedEvent += wm_PostRequestCompletedEvent;
wm.test();
}
void wm_PostRequestCompletedEvent(object sender, EventArgs e)
{
// notify frm2 that thread was finished
}
}