标签:style blog class code java ext
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Runtime.Remoting.Messaging; namespace ConsoleApplication1 { class Program { public delegate int AddDelegate(int op1, int op2);//声明AddDelegate委托 /// <summary> /// 异步调用 /// </summary> /// <param name="args"></param> static void Main(string[] args) { YiBu(); Console.ReadLine(); } #region 同步 /// <summary> /// 同步调用 /// </summary> /// <param name="args"></param> static void TongBu() { AddDelegate addDelegate = new AddDelegate(delegate(int a, int b) { Thread.Sleep(5000); return a + b; }); int result = addDelegate.Invoke(1, 2); //调用Invoke之后会在此处阻塞,后面的代码需要上面的代码执行完之后才能执行,这就是同步调用的坏处:用户体验不好。 Console.WriteLine("此内容只能等到上面的方法执行完之后才会到这里!"); Console.WriteLine(result); } #endregion #region 异步 /// <summary> /// 异步调用 /// </summary> /// <param name="args"></param> static void YiBu() { AddDelegate addDelegate = new AddDelegate(delegate(int a, int b) { Thread.Sleep(5000); return a + b; }); IAsyncResult result = addDelegate.BeginInvoke(1, 2, null, null);//此处是两个null Console.WriteLine("eee"); int m = addDelegate.EndInvoke(result); //异步在调用EndInvoke后会被阻塞,后面的代码也需要等待上面的代码执行完之后才能执行。 Console.WriteLine("此结果需要上面的代码执行完之后才会出来:" + m); } #endregion #region 回调 static void HuiDiao() { AddDelegate addDelegate = new AddDelegate(delegate(int a, int b) { Thread.Sleep(5000); return a + b; }); AsyncCallback callBack = new AsyncCallback(AddComplete); IAsyncResult result = addDelegate.BeginInvoke(1, 2, callBack, "111111111"); Console.WriteLine("此段会直接输出来。不用等待上面代码执行完。此种方式,用户体验号。"); } static void AddComplete(IAsyncResult result) { AddDelegate handler = (AddDelegate)((AsyncResult)result).AsyncDelegate; Console.WriteLine(handler.EndInvoke(result)); Console.WriteLine(result.AsyncState); } #endregion } }
相关文献:http://hi.baidu.com/smithallen/item/b1895d3779945cf02784f4b1
标签:style blog class code java ext
原文地址:http://www.cnblogs.com/pnljs/p/3717870.html