public delegate string WriteLines();
public delegate int MathDelegate(int x);
static void Main(string[] args)
{
#region 同步
//MathClass addClass = new MathClass();
//MathDelegate mathDel = new MathDelegate(addClass.Add); //同步执行
//int syncResult = mathDel(8);
//Console.WriteLine("Sync Proccessing operation...");//这一行只有SyncMethod完成以后才能显示
//Console.WriteLine("Sync Result is: {0}", syncResult);
//Console.ReadLine();
//当程序执行到 int syncResult = mathDel(8); 的时候,主线程将等待至少1秒的时间(Add方法的执行),才能执行
//后面的代码,也即在期间,应用程序没有响应,不能执行其他的任何操作,直到Add方法返回结果。
#endregion
#region 异步
/*
MathClass addClass = new MathClass();
WriteLines write = new WriteLines(addClass.show);
MathDelegate mathDel = new MathDelegate(addClass.Add);
IAsyncResult isa = write.BeginInvoke(null,null);
string a = write.EndInvoke(isa);
Console.WriteLine(a);
IAsyncResult async = mathDel.BeginInvoke(9, null, null);//在另外的线程里,调用Add方法 , BeginInvoke返回IAsyncResult,这个结果可用于监视异步调用的进度;
Console.WriteLine("Async Proccessing operation...");//立即打印到终端设备
int asyncReuslt = mathDel.EndInvoke(async);
Console.WriteLine("Result is: {0}", asyncReuslt);
Console.ReadLine();
**/
//在这段代码中,在开始并没有直接调用方法,而是使用BeginInvoke()方法,返回IAsyncResult
#endregion
#region 代码三,IsCompleted,轮询异步调用完成
/* MathClass addClass = new MathClass();
MathDelegate mathDel = new MathDelegate(addClass.Add);
IAsyncResult async = mathDel.BeginInvoke(9, null, null);//在另外的线程里,调用Add方法
Console.WriteLine("Async Proccessing operation...");//立即打印到终端设备
int i = 1;
while (async.IsCompleted == false) //使用IAsyncResult实例的IsCompleted属性,以获取异步操作是否已完成的指示,如果操作完成则为True,否则为False。
{
Thread.Sleep(i * 1000);
Console.WriteLine("IsCompleted:{0},{1}", async.IsCompleted, i);
i++;
}
int asyncReuslt = mathDel.EndInvoke(async);
Console.WriteLine("Result is: {0}", asyncReuslt);
Console.ReadLine();**/
#endregion
#region 代码四,AsyncCallback,异步调用完成时执行回调方法
/*
* 如果启动异步调用的线程不需要是处理结果的线程,则可以在调用完成时执行回调方法;
如果要使用回调方法,必须将引用回调方法AsyncCallback委托传递给BeginInvoke()方法,也可以传递包含回调方法将要使用的信息的对象。
* */
MathClass addClass = new MathClass();
MathDelegate mathDel = new MathDelegate(addClass.Add);
IAsyncResult async = mathDel.BeginInvoke(9, new AsyncCallback(CompleteMethod), "信息来自于主线程");//在另外的线程里,调用Add方法
Console.WriteLine("Async Proccessing operation...");//立即打印到终端设备
Console.ReadLine();
}
private static void CompleteMethod(IAsyncResult async)
{
AsyncResult ar = (AsyncResult)async;//封装异委托作上异步步操的方法
MathDelegate del = (MathDelegate)ar.AsyncDelegate;
int result = del.EndInvoke(async);
string mainTheadMsg = ar.AsyncState as string;
Console.WriteLine("{0}, Result is: {1}", mainTheadMsg, result);
}
#endregion