需要再复习 注意: 难精通+易使用+功能强大东西,一旦被滥用后果非常严重
缺点1:这是一种方法级别紧耦合,显示工作中要慎之又慎
缺点2:使可读性下降,debug的难度增加
缺点3:把委托回调、异步调用和多线程纠缠在一起,会让代码变得难以阅读和维护
缺点4:委托使用不当有可能造成内存泄漏和程序性能下降
多播委托–同步调用
安装封装方法的先后顺序执行
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student() { ID = 1, PenColor = ConsoleColor.Red };
Student stu2 = new Student() { ID = 2, PenColor = ConsoleColor.Green };
Student stu3 = new Student() { ID = 3, PenColor = ConsoleColor.Yellow };
Action action1 = new Action(stu1.DoHomework);
Action action2 = new Action(stu2.DoHomework);
Action action3 = new Action(stu3.DoHomework);
action1();
action1.Invoke();
action2();
action2.Invoke();
action3();
action3.Invoke();
action1 += action2;
action1 += action3;
action1.Invoke();
}
}
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}",this.ID,i);
//睡眠1秒钟
Thread.Sleep(1000);
}
}
}
串行同步单线程
并行异步多线程
隐式异步调用
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student() { ID = 1, PenColor = ConsoleColor.Red };
Student stu2 = new Student() { ID = 2, PenColor = ConsoleColor.Green };
Student stu3 = new Student() { ID = 3, PenColor = ConsoleColor.Yellow };
Action action1 = new Action(stu1.DoHomework);
Action action2 = new Action(stu2.DoHomework);
Action action3 = new Action(stu3.DoHomework);
action1.BeginInvoke(null,null);
action2.BeginInvoke(null, null);
action3.BeginInvoke(null, null);
for (int i = 0; i < 10; i++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Main thread{0}",i);
Thread.Sleep(1000);
}
}
}
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}",this.ID,i);
//睡眠1秒钟
Thread.Sleep(1000);
}
}
}
显式异步调用
谁都不等谁,还会争抢资源
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student() { ID = 1, PenColor = ConsoleColor.Red };
Student stu2 = new Student() { ID = 2, PenColor = ConsoleColor.Green };
Student stu3 = new Student() { ID = 3, PenColor = ConsoleColor.Yellow };
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();
for (int i = 0; i < 10; i++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Main thread{0}",i);
Thread.Sleep(1000);
}
}
}
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}",this.ID,i);
//睡眠1秒钟
Thread.Sleep(1000);
}
}
}