C# 多线程编程 使用Thread类创建线程

使用Thread类可以创建和控制线程。使用Thread类需要引入系统的System.Threading命名空间。

下面简单示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadDemo
{
    class Program
    {
        static void ThreadMain()
        {
            Console.WriteLine("Running in the thread {0}, id: {1}",Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId);
        }

        static void Main(string[] args)
        {
            Thread t1 = new Thread(ThreadMain);
            t1.Name = "MyThread";
            t1.Start();
            Console.WriteLine("This is the Main thread");

            Console.ReadKey();            
        }
    }
}

这里不能保证哪个结果显输出,线程由操作系统调度,每次哪个线程在前面是不同的。

使用Thread类创建的线程默认的是前台线程,线程池中的线程总是后台线程。

  • 前台线程
  • 后台线程

前台线程在Main方法结束后,还会执行,一直到所有前台线程都完成任务了,程序才会结束。

后台线程在Main方法结束的时候,也会随之一起结束。

后台线程非常适合完成后台任务。例如关闭WORD应用程序,拼写检查继续运行其进程就没有意义。这样可以将这个进程设置为后台进程。

通过设置线程的IsBackground属性可以设置是否为后台进程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ForegroundThread
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(ThreadMain);
            t1.Name = "MyNewThread1";
            t1.IsBackground = true;
            t1.Start();
            Console.WriteLine("Main Thread ending now...");
        }

        static void ThreadMain()
        {
            Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name);
            Thread.Sleep(3000);
            Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name);
        }
    }
}
原文地址:https://www.cnblogs.com/herbert/p/1765240.html