《.NET本质论》上写得很清楚,建议看看这本书
下面这段代码,是个小实例,说明异步Delegate是如何使用的:
设计了两个代理,一个是有返回值的,一个是没有返回值的。
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("GetDate process is begin.");
GetDateDelegate gd = new GetDateDelegate(this.GetCurrentDate);
gd.BeginInvoke(new AsyncCallback(this.CallbackMethod),null);
}
// Invoke a complex process.
private void button2_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Complex process is begin.");
ComplexProcessDelegate cpd =
new ComplexProcessDelegate(this.DoComplexWork);
// cpd(); // synchornized invoke.
IAsyncResult iar = cpd.BeginInvoke(null, null); // aynchornized invoke.
// iar.AsyncWaitHandle.WaitOne(); // waiting util the process is over.
// Synchornized ...
MessageBox.Show("Complex process is end.");
}
private void DoComplexWork()
{
System.Threading.Thread.Sleep(5000);
}
private string GetCurrentDate()
{
System.Threading.Thread.Sleep(5000);
return DateTime.Now.ToString();
}
private void CallbackMethod(IAsyncResult iar)
{
AsyncResult ar = (AsyncResult) iar;
GetDateDelegate gd = (GetDateDelegate) ar.AsyncDelegate;
string msg = gd.EndInvoke(iar);
MessageBox.Show(msg);
}
public delegate void ComplexProcessDelegate();
public delegate string GetDateDelegate();
delegate的BeginInvoke和EndInvoke的小例子
最新推荐文章于 2024-06-19 15:38:44 发布