Delegate学习之使用委托进行异步编程
2010-02-26 22:30 爱研究源码的javaer 阅读(259) 评论(0) 编辑 收藏 举报异步委托提供以异步方式调用同步方法的能力。当同步调用一个委托时,“Invoke”方法直接对当前线程调用目标方法。如果编译器支持异步委托,则它将生成“Invoke”方法以及“BeginInvoke”和“EndInvoke”方法。如果调用“BeginInvoke”方法,则公共语言运行库 (CLR) 将对请求进行排队并立即返回到调用方。将对来自线程池的线程调用该目标方法。提交请求的原始线程自由地继续与目标方法并行执行,该目标方法是对线程池线程运行的。如果在对“BeginInvoke”方法的调用中指定了回调方法,则当目标方法返回时将调用该回调方法。在回调方法中,“EndInvoke”方法获取返回值和所有输入/输出参数。如果在调用“BeginInvoke”时未指定任何回调方法,则可以从调用“BeginInvoke”的线程中调用“EndInvoke”。
要点 |
---|
使用用户指定的委托签名,编译器应发出具有“Invoke”、“BeginInvoke”和“EndInvoke”方法的委托类。“BeginInvoke”和“EndInvoke”方法应被修饰为本机的。因为这些方法被标记为本机的,所以 CLR 在类加载时自动提供该实现。加载程序确保它们未被重写。 |
摘自:http://msdn.microsoft.com/zh-cn/22t547yb(VS.80).aspx
Delegate异步调用参考代码:
public delegate int AddDelegate(int x, int y);
class Program9 {
static void
Console.WriteLine("Client application started! ");
Thread.CurrentThread.Name = "Main Thread";
Calculator cal = new Calculator();
AddDelegate del = new AddDelegate(cal.Add);
string data = "Any data you want to pass.";
AsyncCallback callBack = new AsyncCallback(OnAddComplete);
del.BeginInvoke(2, 5, callBack, data); // 异步调用方法
// 做某些其它的事情,模拟需要执行3秒钟
for (int i = 1; i <= 3; i++) {
Thread.Sleep(TimeSpan.FromSeconds(i));
Console.WriteLine("{0}: Client executed {1} second(s).",
Thread.CurrentThread.Name, i);
}
Console.WriteLine(" Press any key to exit...");
Console.ReadKey();
}
static void OnAddComplete(IAsyncResult asyncResult) {
AsyncResult result = (AsyncResult)asyncResult;
AddDelegate del = (AddDelegate)result.AsyncDelegate;
string data = (string)asyncResult.AsyncState;
int rtn = del.EndInvoke(asyncResult);
Console.WriteLine("{0}: Result, {1}; Data: {2} ",
Thread.CurrentThread.Name, rtn, data);
}
}
public class Calculator { /* 与上面同,略 */}
转自:http://www.cnblogs.com/JimmyZhang/archive/2008/08/22/1274342.html