c# 使用 Thread C# 中怎样使用Thread

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c# 使用 Thread C# 中怎样使用Thread

一线码农   2021-01-28 我要评论

线程是进程中的最小执行单元,多线程是指在给定时间内拥有多个线程的能力,并且可以调度它们从而在某一时刻处理多个操作,微软的 .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() 方法都是被标记成弃用的状态了,取而代之的做法是:使用 AutoResetEventEventWaitHandle 方法来实现多线程之间的同步。

设置线程优先级

可以给一个线程赋予优先级,从而和内存中的其他线程争抢 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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们