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