栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

如何在 C# 中使用 Thread

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在 C# 中使用 Thread

线程是进程中的最小执行单元,多线程是指在给定时间内拥有多个线程的能力,并且可以调度它们从而在某一时刻处理多个操作,微软的 .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) 是一个非常好的做法,毕竟线程池内部会帮你自动创建,释放,调度线程,你只需要傻傻的用即可,同时也是提升程序响应的利器。

更多高质量干货:参见我的 GitHub: [csharptranslate] github.com/ctripxchuang/csharptranslate

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号