我们有一个打开ParentForm
的Windows窗体ChildForm
。如下所示:
var form = new ChildForm(parm1, parm2, parm3, parm4);
form.StartPosition = FormStartPosition.CenterParent;
form.ShowDialog();
ChildForm
的构造函数如下所示:
public ChildForm(string Parm1, string Parm2, string Parm3, string Parm4)
{
InitializeComponent();
FillThisComboBox();
FillThisOtherComboBox();
BindAnotherCombobox();
BindGridview();
FillCheckBoxList();
FillAnotherCheckBoxList();
}
不幸的是,ChildForm
需要一段时间才能加载,因为它在实际绘制表单之前运行所有这些方法。
我想使用async await
执行所有这些方法,以便在所有ekse运行时绘制表单,并且我尝试了类似下面的内容,但我继续遇到构建错误:
private async void ChildForm_Load(object sender, EventArgs e)
{
await PrepareControls();
}
private async Task PrepareControls()
{
FillThisComboBox();
FillThisOtherComboBox();
BindAnotherCombobox();
BindGridview();
FillCheckBoxList();
FillAnotherCheckBoxList();
}
感谢任何帮助。感谢。
答案 0 :(得分:3)
Async / Await有一些规则如下:
使其他方法异步通常遵循以下模式:
public async Task<ofSomething> DoSomething(){
//entry here is on the caller's thread.
var x =await Task<ofSomething>.Run(()=>{
//this code will be run independent of calling thread here
return GetSomething();
}
//at this point you are back on the caller's thread.
//the task.result is returned.
return x;
}
每个异步方法都有一个或多个语句&#34;等待&#34;一个值。变量x是&#34;关闭正在返回OfSomeThing类型的GetSomething结果的任务。
要使用上面的代码,请在eventhanlder中返回void ...如您所知,您必须输入async关键字
public async void ClickEventHandler(object sender, EvantArgs e){
var x = await DoSomething();
//var x now has the ofSomething object on the gui thread here.
}
请注意,click处理程序返回void以满足clickhandler的委托签名,但它调用的异步方法不返回void。
并发,错误处理和取消都很重要,所以也要研究它们。欢迎来到Async世界。 Async世界让事情变得更加容易。
答案 1 :(得分:0)
查看我的两个表单项目。您可以使用表单实例在构造函数和加载函数之后调用PrepareControls。您可以使用form.Show()或form.ShowDialog(),具体取决于您是否要等待子窗体关闭或不关闭。
表格1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2(this);
}
private void button1_Click(object sender, EventArgs e)
{
form2.Show();
string results = form2.GetData();
}
}
}
表格2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 nform1)
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form2_FormClosing);
form1 = nform1;
form1.Hide();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
//stops form from closing
e.Cancel = true;
this.Hide();
}
public string GetData()
{
return "The quick brown fox jumped over the lazy dog";
}
}
}