• C#编程 线程,任务和同步(2) 开启线程


    创建线程的几种方法:

    1 异步委托

    创建线程的一种简单方式是定义一个委托,并异步调用它。 委托是方法的类型安全的引用。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();
            }
        }
    }
    

    2 通过Thread类

     我们可以通过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();
            }
        }
    }
    

    输出结果:

    下面我们传递一个对象的普通方法,先定义一个类:

    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();
            }
        }
    }
    

    3 使用线程池

    创建线程需要时间。 如果有不同的小任务要完成,就可以事先创建许多线程 , 在应完成这些任务时发出请求。 这个线程数最好在需要更多的线程时增加,在需要释放资源时减少。

    不需要 自己创建线程池,系统已经有一个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();
    
            }
        }
    }
    

    输出结果:

    4 通过任务创建

    在.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 ");
  • 相关阅读:
    《深入了解 Linq to SQL》之对象的标识 —— 麦叔叔呕心呖血之作
    闲聊吉日与水军
    谈谈需求的变更
    ALinq BUG & 版本发布
    Linq to SQL (ALinq) 也来AOP —— ALinq Inject 博客园首发
    使用Orachard与Bootstrap建站心得
    一位软件作者的吐嘈——读《Google Reader猝死启示录:互联网无法永远免费》有感
    被神化的架构和被夸大的CTRL+C、CTRL+V
    我对程序员技能的一些认识
    又见ORM跑分 —— 对ORM跑分的吐嘈
  • 原文地址:https://www.cnblogs.com/lmx282110xxx/p/10798680.html
Copyright © 2020-2023  润新知