C# 中的线程
线程定义为程序的执行路径。每个线程定义一个独特的控制流程。如果你的应用程序涉及复杂且耗时的操作,那么设置不同的执行路径或线程通常会有所帮助,每个线程执行特定的作业。
线程的生命周期从创建 System.Threading.Thread 类的对象开始,并在线程终止或完成执行时结束。
以下是线程生命周期中的各种状态 −
未启动状态 - 创建线程实例但未调用 Start 方法时的情况。
就绪状态 - 线程准备运行并等待 CPU 周期的情况。
不可运行状态 - 线程不可执行,当
- 已调用睡眠方法
- 已调用等待方法
- 被 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP