用委托写异步编程的方法介绍:
--第一步,首先写出你要干的事情
--比如说一个加法函数
public int Add (int x, int y)
{
.....
}
--第二步,声明委托
public delegate int DelegateAdd (int i , int j) ;
--记得这里的写法就是你的函数方法多加一个delegate关键字而已
--第三步,写回调函数
public void AddComplete (IAsyncResult iAr)
{
AsyncResult ar = (AsyncResult)iAr ;
DelegateAdd d = (DelegateAdd)ar.AsyncDelegare ;
结果=d.EndInvoke(iAr);
//下面是主线程往回调函数里传入的消息
//可有可无
消息= (消息的类型)iAr.AsyncState ;
//对这段信息进行处理
}
//这个回调函数的写法是
//返回值一定是void
//函数的参数一定是 IAsyncResult
//函数里面就看你怎么处理了
--最后一步,委托的调用
--第一步,首先写出你要干的事情
--比如说一个加法函数
public int Add (int x, int y)
{
.....
}
--第二步,声明委托
public delegate int DelegateAdd (int i , int j) ;
--记得这里的写法就是你的函数方法多加一个delegate关键字而已
--第三步,写回调函数
public void AddComplete (IAsyncResult iAr)
{
AsyncResult ar = (AsyncResult)iAr ;
DelegateAdd d = (DelegateAdd)ar.AsyncDelegare ;
结果=d.EndInvoke(iAr);
//下面是主线程往回调函数里传入的消息
//可有可无
消息= (消息的类型)iAr.AsyncState ;
//对这段信息进行处理
}
//这个回调函数的写法是
//返回值一定是void
//函数的参数一定是 IAsyncResult
//函数里面就看你怎么处理了
--最后一步,委托的调用
DelegateAdd da = new DelegateAdd (Add);
下面是一个完整的例子
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace 委托练习4callback和传入信息
{
public delegate int BinaryOp (int i , int j);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("async call back and send msg");
Console.WriteLine("main() invoke on thread{0}",
Thread.CurrentThread.GetHashCode());
BinaryOp b = new BinaryOp(Add);
b.BeginInvoke(10, 20,
new AsyncCallback(AddComplete), "太好了");
//这下面就可以做自己喜欢的事了,不会阻塞
for (int i = 0; i < 10; i++)
{
Console.WriteLine("无聊{0}",
Thread.CurrentThread.GetHashCode());
}
Console.Read();
}
static int Add(int i , int j)
{
Console.WriteLine("add() invoke on thread{0}",
Thread.CurrentThread.GetHashCode());
Thread.Sleep(3000);
return i + j;
}
static void AddComplete(IAsyncResult iAr)
{
Console.WriteLine("AddComplete() invoke on thred{0}",
Thread.CurrentThread.GetHashCode());
Console.WriteLine("you addition is complete");
//得到结果
AsyncResult ar = (AsyncResult)iAr;
BinaryOp b = (BinaryOp)ar.AsyncDelegate;
int answer = b.EndInvoke(iAr);
Console.WriteLine("10+20={0}", answer);
//主线程向addComplete传入消息
string msg = (string)iAr.AsyncState;
Console.WriteLine("主线程向addcomplete()传入了一段文本:{0}",
msg);
}
}
}