C# 中的线程
线程定义为程序的执行路径。每个线程定义一个独特的控制流。如果你的应用程序包含复杂且耗时的操作,则通常可以设置不同的执行路径或线程,每个线程执行特定的作业。
线程的生命周期从创建 System.Threading.Thread 类的对象时开始,并在线程终止或完成执行时结束。
以下是线程生命周期中的各个状态 -
未启动状态 - 是指创建了线程的实例但未调用 Start 方法的情况。
就绪状态 - 是指线程已准备好运行并等待 CPU 周期的情况。
不可运行状态 - 当
- 调用了 Sleep 方法时
- 调用了 Wait 方法时
- 被 I/O 操作阻塞时线程不可执行。
死亡状态 - 是指线程完成执行或被中止的情况。
以下是一个示例,显示如何创建线程 -
示例
using System;
using System.Threading;
namespace Demo {
class Program {
public static void ThreadFunc() {
Console.WriteLine("Child thread starts");
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(ThreadFunc);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}输出
In Main: Creating the Child thread Child thread starts
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP