您的位置:首页 > 其它

delegate的BeginInvoke和EndInvoke的小例子

2009-12-30 16:58 281 查看
《.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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: