标签:read new star console 基础 分支 基础上 dstar 资源
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.隐式异步调用
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); } } }
应当适时使用接口取代对委托的使用
标签:read new star console 基础 分支 基础上 dstar 资源
原文地址:https://www.cnblogs.com/1521681359qqcom/p/11216382.html