建立线程的一种简单方式是定义一个委托,并异步调用它。 委托是方法的类型安全的引用。Delegate类 还支持异步地调用方法。在后台,Delegate类会建立一个执行任务的线程。编程
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _016_线程_委托方式发起线程 { class Program { //通常咱们会为比较耗时的操做 开启单独的线程去执行,好比下载操做 static int Test(int i, string str) { Console.WriteLine("test:" + i + str); Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms return 100; } static void Main(string[] args) {//在main线程中执行 一个线程里面语句的执行 是从上到下的 // 经过委托 开启一个线程 Func<int, string, int> a = Test; // 开启一个新的线程去执行 a所引用的方法 IAsyncResult ar = a.BeginInvoke(100, " mytest", null, null); // IAsyncResult 能够取得当前线程的状态 Console.WriteLine("main"); while (ar.IsCompleted == false)//若是当前线程没有执行完毕 { Console.Write("."); Thread.Sleep(10); //控制子线程的检测频率 } int res = a.EndInvoke(ar);//取得异步线程的返回值 Console.WriteLine(res); } } }
输出结果:安全
上面是经过循环检测判断线程是否结束。当咱们经过BeginInvoke开启一个异步委托的时候,返回的结果是IAsyncResult,咱们能够经过它的AsyncWaitHandle属性访问等待句柄。这个属性返回一个WaitHandler类型的对象,它中的WaitOne()方法能够等待委托线程完成其任务,WaitOne方法能够设置一个超时时间做为参数(要等待的最长时间),若是发生超时就返回false。多线程
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _016_线程_委托方式发起线程 { class Program { //通常咱们会为比较耗时的操做 开启单独的线程去执行,好比下载操做 static int Test(int i, string str) { Console.WriteLine("test:" + i + str); Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms return 100; } static void Main(string[] args) {//在main线程中执行 一个线程里面语句的执行 是从上到下的 // 经过委托 开启一个线程 Func<int, string, int> a = Test; IAsyncResult ar = a.BeginInvoke(100, " mytest", null, null);// 开启一个新的线程去执行 a所引用的方法 // IAsyncResult 能够取得当前线程的状态 Console.WriteLine("main"); //检测线程结束 bool isEnd = ar.AsyncWaitHandle.WaitOne(1000);//1000毫秒表示超时时间,若是等待了1000毫秒 线程尚未结束的话 那么这个方法会返回false 若是在1000毫秒之内线程结束了,那么这个方法会返回true if (isEnd) { int res = a.EndInvoke(ar); Console.WriteLine(res); } } } }
等待委托的结果的第3种方式是使用异步回调。在BeginInvoke的第三个参数中,能够传递一个知足AsyncCallback委托的方法,AsyncCallback委托定义了一个IAsyncResult类型的参数其返回类型是void。对于最后一个参数,能够传递任意对象,以便从回调方法中访问它。异步
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _016_线程_委托方式发起线程 { class Program { //通常咱们会为比较耗时的操做 开启单独的线程去执行,好比下载操做 static int Test(int i, string str) { Console.WriteLine("test:" + i + str); Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms return 100; } static void Main(string[] args) {//在main线程中执行 一个线程里面语句的执行 是从上到下的 Console.WriteLine("main"); //经过回调 检测线程结束 Func<int, string, int> a = Test; // 倒数第二个参数是一个委托类型的参数,表示回调函数,就是当线程结束的时候会调用这个委托指向的方法 倒数第一个参数用来给回调函数传递数据 IAsyncResult ar = a.BeginInvoke(100, " mytest", OnCallBack, a); Console.ReadKey(); } static void OnCallBack( IAsyncResult ar ) { Func<int, string, int> a = ar.AsyncState as Func<int, string, int>; int res = a.EndInvoke(ar); Console.WriteLine(res+"在回调函数中取得结果"); } } }
在第三种方法中,咱们可使用Lamba表达式异步编程
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _016_线程_委托方式发起线程 { class Program { //通常咱们会为比较耗时的操做 开启单独的线程去执行,好比下载操做 static int Test(int i, string str) { Console.WriteLine("test:" + i + str); Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms return 100; } static void Main(string[] args) { Console.WriteLine("main"); //经过回调 检测线程结束 Func<int, string, int> a = Test; a.BeginInvoke(100, "siki", ar => { int res = a.EndInvoke(ar); Console.WriteLine(res + "在lambda表达式中取得"); }, null); Console.ReadKey(); } } }
咱们能够经过Thread类来建立线程,咱们构造一个thread对象的时候,能够传递一个静态方法,也能够传递一个对象的普通方法。咱们先传递一个静态方法:函数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _017_线程_经过Thread发起线程 { class Program { // 注意:线程调用的方法定义中,参数要用object static void DownloadFile(object filename) { // Thread.CurrentThread.ManagedThreadId表示当前线程ID Console.WriteLine("开始下载:" +Thread.CurrentThread.ManagedThreadId +filename); Thread.Sleep(2000); Console.WriteLine("下载完成"); } static void Main(string[] args) { //建立线程,传入要执行的方法 Thread t = new Thread(DownloadFile); // 开启线程,若是线程调用的方法有参数,在Start中传入 t.Start("test"); Console.WriteLine("Main"); Console.ReadKey(); // 使用Lamba表达式方法 //Thread t = new Thread(() => //{ // Console.WriteLine("开始下载:" + Thread.CurrentThread.ManagedThreadId); // Thread.Sleep(2000); // Console.WriteLine("下载完成"); //}); //t.Start(); } } }
输出结果:this
下面咱们传递一个对象的普通方法,先定义一个类:spa
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _017_线程_经过Thread发起线程 { class MyThread { private string filename; private string filepath; public MyThread(string fileName, string filePath) { this.filename = fileName; this.filepath = filePath; } public void DownFile() { Console.WriteLine("开始下载"+filepath+filename); Thread.Sleep(2000); Console.WriteLine("下载完成"); } } }
而后建立线程:线程
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _017_线程_经过Thread发起线程 { class Program { static void Main(string[] args) { MyThread my = new MyThread("xxx.bt","http://www.xxx.bbs"); Thread t = new Thread(my.DownFile); t.Start(); } } }
建立线程须要时间。 若是有不一样的小任务要完成,就能够事先建立许多线程 , 在应完成这些任务时发出请求。 这个线程数最好在须要更多的线程时增长,在须要释放资源时减小。3d
不须要 本身建立线程池,系统已经有一个ThreadPool类管理线程。 这个类会在须要时增减池中线程的线程数,直到达到最大的线程数。 池中的最大线程数是可配置的。 在双核 CPU中 ,默认设置为1023个工做线程和 1000个 I/o线程。也能够指定在建立线程池时应当即启动的最小线程数,以及线程池中可用的最大线程数。 若是有更多的做业要处理,线程池中线程的个数也到了极限,最新的做业就要排队,且必须等待线程完成其任务。
使用线程池须要注意的事项:
线程池中的全部线程都是后台线程 。 若是进程的全部前台线程都结束了,全部的后台线程就会中止。 不能把入池的线程改成前台线程 。
不能给入池的线程设置优先级或名称。
入池的线程只能用于时间较短的任务。 若是线程要一直运行(如 Word的拼写检查器线程),就应使用Thread类建立一个线程。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _018_线程_线程池 { class Program { // 注意:使用线程池添加的执行函数,必需要有一个object类型的参数,即时不用 static void ThreadMethod(object state) { Console.WriteLine("线程开始:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); Console.WriteLine("线程结束"); } static void Main(string[] args) { //开启一个工做线程 ThreadPool.QueueUserWorkItem(ThreadMethod); ThreadPool.QueueUserWorkItem(ThreadMethod); ThreadPool.QueueUserWorkItem(ThreadMethod); ThreadPool.QueueUserWorkItem(ThreadMethod); ThreadPool.QueueUserWorkItem(ThreadMethod); ThreadPool.QueueUserWorkItem(ThreadMethod); ThreadPool.QueueUserWorkItem(ThreadMethod); Console.ReadKey(); } } }
输出结果:
在.NET4 新的命名空间System.Threading.Tasks包含了类抽象出了线程功能,在后台使用的ThreadPool进行管理的。任务表示应完成某个单元的工做。这个工做能够在单独的线程中运行,也能够以同步方式启动一个任务。 任务也是异步编程中的一种实现方式。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _019_线程_任务 { class Program { static void ThreadMethod() { Console.WriteLine("任务开始"); Thread.Sleep(2000); Console.WriteLine("任务结束"); } static void Main(string[] args) { // 经过Task建立 Task t = new Task(ThreadMethod); t.Start(); // 经过任务工厂建立 //TaskFactory tf = new TaskFactory(); //Task t = tf.StartNew(ThreadMethod); Console.WriteLine("Main"); Console.ReadKey(); } } }
输出结果:
连续任务:若是一个任务t1的执行是依赖于另外一个任务t2的,那么就须要在这个任务t2执行完毕后才开始执行t1。这个时候咱们可使用连续任务。
static void DoFirst(){ Console.WriteLine("do in task : "+Task.CurrentId); Thread.Sleep(3000); } static void DoSecond(Task t){ Console.WriteLine("task "+t.Id+" finished."); Console.WriteLine("this task id is "+Task.CurrentId); Thread.Sleep(3000); } Task t1 = new Task(DoFirst); Task t2 = t1.ContinueWith(DoSecond); Task t3 = t1.ContinueWith(DoSecond); Task t4 = t2.ContinueWith(DoSecond);
任务层次结构:咱们在一个任务中启动一个新的任务,至关于新的任务是当前任务的子任务,两个任务异步执行,若是父任务执行完了可是子任务没有执行完,它的状态会设置为WaitingForChildrenToComplete,只有子任务也执行完了,父任务的状态就变成RunToCompletion
static void Main(){ var parent = new Task(ParentTask); parent.Start(); Thread.Sleep(2000); Console.WriteLine(parent.Status); Thread.Sleep(4000); Console.WriteLine(parent.Status); Console.ReadKey(); } static void ParentTask(){ Console.WriteLine("task id "+Task.CurrentId); var child = new Task(ChildTask); child.Start(); Thread.Sleep(1000); Console.WriteLine("parent started child , parent end"); } static void ChildTask(){ Console.WriteLine("child"); Thread.Sleep(5000); Console.WriteLine("child finished ");