概述

无论学习那门编程语言,多线程都是逃不掉的一个坎。为了提升程序整体的运行效率,我们一般都会把比较耗时的程序片段专门开一个单独的线程去处理,这样就可以在同一时间段并行的处理多件事。比如:我们日常生活中烧水就是一个耗时的动作,我们在接好水打开开关以后,我们就可以先去先去做其他的事,而不是一直等到水烧开了才能干其他的事.接下来我就通过实例列举C#中通过thread开启线程的多种方式。

Thread开启线程

1. 启动不带参数线程的方法:

①通过匿名委托快速启动:

Thread t = new Thread( => { for (int i = 0; i < 10; i ) { Console.WriteLine($"第{i 1}秒"); Thread.Sleep(1000); } }); t.Start;

②常规启动:

static void Main(string[] args) { Thread t = new Thread(ThreadFuc); t.Start; Console.ReadKey; } public static void ThreadFuc { for (int i = 0; i < 10; i ) { Console.WriteLine($"第{i 1}秒"); Thread.Sleep(1000); } }

我们这里是通过实例化Thread开启线程,Thread构造器有四个重载函数,分别如下:

thread线程操作(CThread开启线程的几种方式)(1)

我们先看第一个构造器的入参是ThreadStart,他其实就是个委托类型,这里我们其实是把new ThreadStart(ThreadFuc)简写了.

public delegate void ThreadStart;

这种开启线程的方式是针对不带参数的方法。Thread创建的线程默认是前台线程,如果要设置为后台线程,需要如下设置:

t.IsBackground = true;

2. 启动一个带参数线程的方法:

方法1:

static void Main(string[] args) { string str = "当前是"; Thread t = new Thread( => ThreadFuc(str)); t.IsBackground = true; t.Start; Console.ReadKey; } public static void ThreadFuc(string str) { for (int i = 0; i < 10; i ) { Console.WriteLine($"{str}第{i 1}秒"); Thread.Sleep(1000); } }

thread线程操作(CThread开启线程的几种方式)(2)

方法2:

static void Main(string[] args) { string str = "当前是"; Thread t = new Thread(ThreadFuc); t.IsBackground = true; t.Start(str); Console.ReadKey; } public static void ThreadFuc(object str) { for (int i = 0; i < 10; i ) { Console.WriteLine($"{str}第{i 1}秒"); Thread.Sleep(1000); } }

这种其实就是用了thread的第二种重载方法

public Thread(ParameterizedThreadStart start);

Thread t = new Thread(new ParameterizedThreadStart(ThreadFuc));

的简写而已.

,