如何在winform中用委托做异步
不好意思,直接上代码了。
Code
delegate void VoidDelegate ();
VoidDelegate vd = DataBind;
vd.EndInvoke(vd.BeginInvoke(null, null));
所以delegate(委托)的基本东西还是要会的。有返回时候的后续操作的版本是:
![](/Images/OutliningIndicators/ContractedBlock.gif)
delegate DataView DataViewDelegate();
private void button1_Click(object sender, EventArgs e)
{
DataViewDelegate dvd = new DataViewDelegate(DataLoad);
dvd.BeginInvoke(DataBind, dvd);
}
private DataView DataLoad()
{
SqlConnection conn = new SqlConnection(@"Data Source=cat\sqlexpress;Initial Catalog=Northwind;Integrated Security=True");
SqlDataAdapter ada = new SqlDataAdapter("select * from orders ;waitfor delay '00:00:5';", conn);
DataTable dt = new DataTable();
conn.Open();
ada.Fill(dt);
conn.Close();
DataView dv = new DataView(dt);
return dv;
}
private void DataBind(IAsyncResult ar)
{
if (ar == null) throw new ArgumentNullException("ar");
DataViewDelegate dvd1 = ar.AsyncState as DataViewDelegate;
System.Diagnostics.Trace.Assert(dvd1 != null, "Invalid object type ");
DataView dv = dvd1.EndInvoke(ar);
VoidDelegate vd = delegate()
{
dataGridView1.DataSource = dv;
this.dataGridView1.Enabled = true;
this.progressBar1.Visible = false;
this.button1.Enabled = true;
};
dataGridView1.Invoke(vd);//由主线程上的控件来invoke委托
}
委托就是用线程来做异步的(个人看法,还没有从书本或网络中了解到)。
关于异步,下一篇是ASP.NET中做异步的例子,比起网络中现有例子更生动的几个做法。