C# 进阶 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

后台线程

  在默认情况下,用Thread类创建的线程是前台线程。在用thread类创建线程时,可以设置IsBackground属性,以确定该线程是前台线程还是后台线程。将线程的IsBackgrond属性设置为false(默认值) 。

using System;
using System.Threading;
namespace test
{
  class Program
  {
      static void Main(string[] args)
      {
          Thread t1 = new Thread(ThreadMethod);
          t1.Name = "ThreadMethod";
          t1.IsBackground = false;   //设置是否为后台线程
          t1.Start();
          Console.WriteLine("Main End!");
      }
      static void ThreadMethod()
      {
          Console.WriteLine(Thread.CurrentThread.Name+" start.");
          Thread.Sleep(3000);           //线程休眠3秒
          Console.WriteLine(Thread.CurrentThread.Name+" end.");
      }
  }
}

  程序运行结果为:

Main End!
ThreadMethod start.
ThreadMethod end.

  当我们将IsBackground属性值改为true时,有时可以看到与上面相同的运行结果——新线程的启动消息,但没有结束消息。去试一试吧,后台线程特别适合于完成后台任务,如关闭word等。