委托的高级使用
- 多播委托(multicast)一个委托里面包含了不止一个方法
static void Main(string[] args) { Student stu1 = new Student() { ID=1,PenColor=ConsoleColor.Yellow}; Student stu2 = new Student { ID = 2, PenColor = ConsoleColor.Green }; Student stu3 = new Student { ID = 3, PenColor = ConsoleColor.Red }; Action action1 = new Action(stu1.DoHomeWork); Action action2 = new Action(stu2.DoHomeWork); Action action3 = new Action(stu3.DoHomeWork); action1 += action2; action1 += action3; action1();//多播委托,根据封装方法的顺序 //action1();//单播委托 //action2();//单播委托 //action3();//单播委托 Console.ReadLine(); } } class Student { public int ID { get; set; } public ConsoleColor PenColor { get; set; } public void DoHomeWork() { for(int i=0;i<5;i++) { Console.ForegroundColor = this.PenColor; Console.WriteLine("Student{0} doing homework {1} hours",this.ID,i); Thread.Sleep(1000); } } }
2.隐式异步调用
- 同步和异步的语言差别,在英语中异步是两个人同时做,同步是我在你的基础上做
- 同步调用与异步调用的对比
- 每个程序都是一个进程(process)
- 每个进程可以有一个或者多个线程(thread)
- 同步调用时在一个线程内
- 异步调用的底层机理是多线程(多线程同时访问资源时,要注意线程之间争夺资源的冲突,这个时候要为线程加锁)
- 串行=同步=单线程,并行=异步=多线程
class Program { static void Main(string[] args) { Student stu1 = new Student() { ID=1,PenColor=ConsoleColor.Yellow}; Student stu2 = new Student { ID = 2, PenColor = ConsoleColor.Green }; Student stu3 = new Student { ID = 3, PenColor = ConsoleColor.Red }; //stu1.DoHomeWork();//直接调用,同步 //stu2.DoHomeWork(); //stu3.DoHomeWork(); Action action1 = new Action(stu1.DoHomeWork);//间接调用,同步 Action action2 = new Action(stu2.DoHomeWork); Action action3 = new Action(stu3.DoHomeWork); //action1 += action2; //action1 += action3; //action1();//多播委托,根据封装方法的顺序//间接调用,同步 //action1();//单播委托//间接调用,同步 //action2();//单播委托 //action3();//单播委托 //委托的异步调用 //action1.BeginInvoke(null,null);//隐式间接的异步调用,会生成一个分支方法,两个参数第一个参数是回调方法,只子线程执行完,需要执行什么东西 //action2.BeginInvoke(null, null);// //action3.BeginInvoke(null, null); //一般的多线程 Thread thread1 = new Thread(new ThreadStart(stu1.DoHomeWork));//显式的直接的异步调用, Thread thread2 = new Thread(new ThreadStart(stu2.DoHomeWork)); Thread thread3 = new Thread(new ThreadStart(stu3.DoHomeWork)); thread1.Start(); thread2.Start(); thread3.Start(); //高级一点带委托的多线程 Task task1 = new Task(new Action(stu1.DoHomeWork));//显式的异步调用 Task task2 = new Task(new Action(stu2.DoHomeWork)); Task task3 = new Task(new Action(stu3.DoHomeWork)); task1.Start(); task2.Start(); task3.Start(); for (int i = 0; i < 10;i++ ) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Main thread{0}",i); Thread.Sleep(1000); } Console.ReadLine(); } } class Student { public int ID { get; set; } public ConsoleColor PenColor { get; set; } public void DoHomeWork() { for(int i=0;i<5;i++) { Console.ForegroundColor = this.PenColor; Console.WriteLine("Student{0} doing homework {1} hours",this.ID,i); Thread.Sleep(1000); } } }
应当适时使用接口取代对委托的使用
- java完全使用接口取代了委托的功能,java没有与C#中委托相对应的实体
- 重构代码一般是指把代码放在更合适的地方