同步,异步,回调例子
2014-05-08 22:52
369 查看
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
相关文章推荐
- boost库学习随记六:使用同步定时器、异步定时器、bind、成员函数回调处理、多线程的同步处理示例等
- C# 同步调用、异步调用、异步回调
- Boost.asio实现的同步、异步TCP通信的简单例子
- java 回调机制分为:异步回调 同步回调
- Python 中的进程、线程、协程、同步、异步、回调
- 线程,任务,同步之异步回调
- 深入浅出:进程、线程、协程、同步、异步、回调(转载)
- java 三种调用机制(同步、回调、异步)
- 从几个例子理解串行并行队列及同步异步任务
- 同步与异步,回调与协程
- 软件接口:同步调用、回调和异步调用
- JAVA异步加回调的例子
- 定时器回调的同步与异步之争
- java 回调的同步回调和异步回调
- Java 回调机制解析(同步回调/异步回调)
- c# 同步委托,异步委托,异步回调
- android 异步回调中操作UI线程,UI同步、卡死阻塞等性能问题
- 异步回调和同步回调
- 同步调用、回调和异步调用的区别
- 关于C10K、异步回调、协程、同步阻塞