异步委托
时间:2010-09-01 来源:iceknp
异步委托的使用:
代码private delegate double RunAsyncEventHandler(double douA, double douB);
private delegate void SetSendTextEventHandler(string strText);
private RunAsyncEventHandler asyncHandler;
private void btnSend_Click(object sender, EventArgs e)
{
asyncHandler = new RunAsyncEventHandler(RunAsync);
asyncHandler.BeginInvoke(5d, 3d, new AsyncCallback(GetAsyncResult), null);
}
public double RunAsync(double douA, double douB)
{
Thread.Sleep(3000);
return douA + douB;
}
public void GetAsyncResult(IAsyncResult result)
{
double douResult = asyncHandler.EndInvoke(result);
//1.第一种方法
this.Invoke(new SetSendTextEventHandler(rtbSend.AppendText),
new object[] { douResult.ToString() + "\n" });
//2.第二种方法
SetSendText(douResult.ToString());
}
public void SetSendText(string strText)
{
if (this.InvokeRequired)
{
SetSendTextEventHandler handler =
new SetSendTextEventHandler(SetSendText);
this.Invoke(handler, new object[] { strText });
}
else
{
lock (rtbSend)
{
rtbSend.AppendText(strText);
rtbSend.AppendText("\n");
}
}
}
在执行RunAsync方法时候,窗体仍然可以继续进行其他操作,异步委托创建的线程是位于线程池中。若有疑问或不正之处,欢迎提出指正和讨论。
相关阅读 更多 +