1、多线程:多线程
一、概念:异步
(线程启动时,调用传过来的委托,委托就会执行相应的方法,实现线程执行方法)ide
案例代码:函数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace _07多线程 { class Program { static void Main(string[] args) { Console.WriteLine("主线程 {0} 正在执行中...", Thread.CurrentThread.ManagedThreadId); #region 线程 //ThreadStart 无参无返回值的委托 Thread thread = new Thread(ShowMsg);//新开启一个线程执行一个方法 //建议操做系统把当前线程搞成高级别 thread.Priority = ThreadPriority.Highest; //给开发人员用,来识别不一样的线程 thread.Name = "zy"; //后台线程: 若是全部的前台线程都退出了,那么后台线程自动被关闭 thread.IsBackground = true; thread.Start();//并无执行,告诉操做系统准备就绪 //thread.Abort();//关闭线程 Console.ReadKey(); #endregion } static void ShowMsg() { Console.WriteLine("工做线程 {0} 执行中...",Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); } } }
运行截图:spa
五、Thread类的一些重要成员:操作系统
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Runtime.Remoting.Messaging; namespace _07多线程 { public delegate int AddDel(int a,int b);//声明一个有参数有返回值的委托 class Program { static void Main(string[] args) { Console.WriteLine("主线程 {0} 正在执行中...", Thread.CurrentThread.ManagedThreadId); AddDel addDel = new AddDel(AddFunc); //1.同步调用 //int c = addDel(1, 2); //2.无回调函数的异步调用 //启动委托指向的方法来执行,具体由线程池提供一个线程来执行当前的委托指向的方法 //IAsyncResult ascResult = addDel.BeginInvoke(1, 2, null, null); //while (!ascResult.IsCompleted) //{ // //主线程执行的其余操做 //} ////此EndInvoke方法会阻塞当前线程。直到委托方法执行完毕后, ////并将返回值交给result后,继续执行后面的代码 //int result = addDel.EndInvoke(ascResult); //Console.WriteLine(result);//3 //Console.ReadKey(); //3.有回调函数的异步调用 IAsyncResult ascResult = addDel.BeginInvoke(1, 2, MyDelCallBack, 3); //主线程可继续执行其余操做 Console.WriteLine("==========="); Console.ReadKey(); } static int AddFunc(int a, int b) { Console.WriteLine("AddFunc工做线程运行中...{0}", Thread.CurrentThread.ManagedThreadId); //Thread.Sleep(1000); return a + b; } //异步委托执行完成了的回调函数 public static void MyDelCallBack(IAsyncResult result) { //把接口类型转换成实例类型 AsyncResult aResult = (AsyncResult)result; //转换成咱们本身的委托类型 AddDel del = (AddDel)aResult.AsyncDelegate; //执行完成获取执行的结果 int addResult = del.EndInvoke(result); int state = (int)aResult.AsyncState;//3 Console.WriteLine("异步完成的回调方法执行的结果是:{0} @{1}", addResult, Thread.CurrentThread.ManagedThreadId); } } }
运行截图:.net
执行步骤:线程
①从线程池里获取一个线程。指针
②执行委托指向的方法(在工做线程里面执行)code
③调用回调函数(若是是null不执行)。