LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

如何在 C# 中使用线程(Thread)

admin
2021年1月29日 9:37 本文热度 2729

线程是进程中的最小执行单元,多线程是指在给定时间内拥有多个线程的能力,并且可以调度它们从而在某一时刻处理多个操作,微软的 .Net Framework 提供了 Thread 来帮助我们完成多线程开发。

Thread 编程

要想使用 Thread,需要在程序中引用 System.Threading 命名空间,然后再提供一个供线程调度的方法,这个方法是通过 Thread 中的 ThreadStart 委托代理的,下面的代码展示了如何创建线程。


Thread t = new Thread(new ThreadStart(MyThreadMethod));

线程创建好之后,还需要调用  Start 方法去启动,下面的代码展示了如何去实现,哦,对了,上面的 MyThreadMethod 方法会在新的线程上被调度,而不是调用线程。


    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(MyThreadMethod));
            t.Start();
            Console.Read();
        }
        static void MyThreadMethod()
        {
            Console.WriteLine("Hello World!");
        }
    }

展示线程状态

一个创建好的线程,它的生命周期内会有多个状态,比如:Aborted, Background, Running, Stopped, Suspended, Unstarted 等等,这些状态在 Thread 中是用 ThreadState 枚举表示的,如下代码所示:


    [Flags]
    public enum ThreadState
    {
        Running = 0,
        StopRequested = 1,
        SuspendRequested = 2,
        Background = 4,
        Unstarted = 8,
        Stopped = 16,
        WaitSleepJoin = 32,
        Suspended = 64,
        AbortRequested = 128,
        Aborted = 256
    }

当一个 Thread 对象创建好之后,它的状态就是 Unstarted,然而当 Start 方法启动之后,线程的状态将会从 Unstarted 切换到 Running 状态,下面的代码展示了这种轮转。


        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(MyThreadMethod));
            Console.WriteLine("The thread''s state is:" + t.ThreadState.ToString());
            t.Start();
            Console.WriteLine("The thread''s state is:" + t.ThreadState.ToString());
        }


控制线程的 前台和后台

一个线程要么是前台线程要么是后台线程,如果你是通过显式的方式创建线程,它便是前台线程,前后线程最大的区别在于:应用程序退出的前提必须是程序内的所有前台线程都得到退出,相反,应用程序的退出不依赖于后台线程。

你可以通过 IsBackground 属性来设置 Thread 的前台或者后台,下面的代码展示了如何去实现。


        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(MyThreadMethod));
            t.Start();
            t.IsBackground = true;
            Console.WriteLine(“The thread’s background status is: “+t.IsBackground.ToString());
            Console.Read();
        }

除了启动线程,还可以通过 Suspend() 和 Resume() 方法来 挂起 和 恢复 线程, 值得注意的是,你只能 恢复 你之前通过 Suspend 方法 挂起的线程,如下代码所示:


        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(MyThreadMethod));
            t.Start();
            t.Suspend(); //Suspends the newly created thread
            t.Resume(); //Resumes the suspended thread
            Console.Read();
        }

值得注意的是,现在的 Thread.Suspend() 和 Thread.Resume() 方法都是被标记成弃用的状态了,取而代之的做法是:使用 AutoResetEvent 和 EventWaitHandle 方法来实现多线程之间的同步。

设置线程优先级

可以给一个线程赋予优先级,从而和内存中的其他线程争抢 CPU 时间,在 C# 中是使用 ThreadPriority 枚举来表示,大体上有如下值:Lowest, BelowNormal, Normal, AboveNormal 和 Highest,下面的代码展示了如何给这两个线程赋予优先级。


    class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(new ThreadStart(Method1));
            Thread thread2 = new Thread(new ThreadStart(Method2));

            thread1.Priority = ThreadPriority.Highest;
            thread2.Priority = ThreadPriority.Lowest;

            thread2.Start();
            thread1.Start();

            Console.Read();
        }
        static void Method1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("First thread: " + i);
            }
        }
        static void Method2()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Second thread: " + i);
            }
        }
    }


从上面的输出结果中可以看出,Thread1 先于 Thread2 执行完,即使 Thread2.Start 是先启动的,是不是很好的演示了优先级的概念。

线程是昂贵的,因为线程的整个生命周期需要消耗太多的资源,比如:初始化,上下文切换,释放使用的资源 等等,所以在用 多线程 之前需要想好是否真的要这么做,当用多线程的时候,适当的使用 线程池 (ThreadPool) 是一个非常好的做法,毕竟线程池内部会帮你自动创建,释放,调度线程,你只需要傻傻的用即可,同时也是提升程序响应的利器。

译文链接:https://www.infoworld.com/article/3035134/how-to-work-with-threads-in-c.html


该文章在 2021/1/29 9:37:40 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved