异步-学习笔记1

1. 同步方法卡界面,因为主线程被占用,无法响应操作;异步多线程方法不卡界面,因为计算机任务交给主线程,主线程(UI线程)闲置。

2. 同步方法慢,因为只有一个主线程工作,但是资源占用少;异步多线程方法快,因为多线程并发计算,但是资源占用多。
    多线程的调度管理是耗资源的。
3. 异步方法启动是无序的,运行也是无序的,结果也是无序的。原因:申请线程并不按照顺序响应,执行过程也不完全相同。

        //同步,操作顺序执行,只有一个线程
private void Synic_Click(object sender, EventArgs e) { Console.WriteLine("****************************Main Thread Begin*****************************"); for (int i=0;i<5;i++) { string threadname = string.Format("SingleThread"); Action<string> threadDelegate = UseTimeMethod; threadDelegate.Invoke(threadname); // Invoke()是同步 } Console.WriteLine("****************************Main Thread End*******************************"); Console.WriteLine(); } //异步 private void Asynic_Click(object sender, EventArgs e) { Console.WriteLine("****************************Main Thread Begin*****************************"); for (int i = 0; i < 5; i++) { string threadname = string.Format("Thread"+i); Action<string> threadDelegate = UseTimeMethod; //委托是异步多线程的基础 threadDelegate.BeginInvoke(threadname,null,null); //BeginInvoke()是异步 } Console.WriteLine("****************************Main Thread End*******************************"); Console.WriteLine(); } //定义一个耗时的方法 public void UseTimeMethod(string threadname) { Console.WriteLine("{0} {1} start ,线程id={2}", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss.fff"),threadname ,Thread.CurrentThread .ManagedThreadId ); int icount = 0; for(int i=0;i<1000000000;i++) { icount=i; } Console.WriteLine("{0} {1} end ,线程id={2},Result={3}", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss.fff"), threadname, Thread.CurrentThread.ManagedThreadId, icount); } }

执行结果:

原文地址:https://www.cnblogs.com/xiao9426926/p/6098076.html